LoginSignup
0
0

Commandパターンについて勉強

Posted at

Commandパターンとは?

命令を実行するオブジェクトと命令の内容のオブジェクトを分離するパターン。

CommandパターンをJSで実装

class Invoke {
  execute(command, ...args) {
    return command.execute(this.operations, ...args);
  }
}

class SelectCommand {
  constructor() {
    this.execute = () => {
      console.log("slect");
    };
  }
}

class InsertCommand {
  constructor() {
    this.execute = () => {
      console.log("insert");
    };
  }
}

const invoke = new Invoke();

invoke.execute(new SelectCommand());
invoke.execute(new InsertCommand());

Commandパターンの使いどころ

  • 命令をオブジェクトをとして宣言したい際に使用
  • 取り消し操作を実装する際

Commandパターンの利点と欠点

利点

  • 操作を実行するオブジェクトとメソッドを切り離せる(単一責任の原則)
  • 単純なコマンドを組み合わせて複雑なものを作成可能
  • コードの詳細を知らなくても、命令を実行可能

欠点

  • コードが複雑になる(命令が増えるとクラスがいっぱい。)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0