LoginSignup
0
0

More than 3 years have passed since last update.

Command Pattern

Last updated at Posted at 2020-11-07

Command Pattern

クラスインスタンスを保存するクラスを作り(command.class)、保存したクラスインスタンスのメソッドをcommand.classメソッドのように扱う。

このページでは
・シンプルなCommandパターン
・メソッド実行回数を表示する機能の追加
について記載します

Design Pattarm MENU

シンプルなCommandパターン

以下の構成とします

クラス 説明
command.interface 登録されるインスタンスを共通化する
samCommand1.class commandを実装しメソッドを一つ持たせる
samCommand2.class commandを実装しメソッドを一つ持たせる
commandPool.class samCommand1とsamCommand2のインスタンスを保存する
user(Main.class) Command.classの動作を確認

*user 他の開発者がこのパターンを利用する、という意味合いを含みます

command.interface
interface command{
  void s();
}
samCommand1.class
class samCommand1 implements command{
  public void s(){System.out.println("command1");}
}
samCommand2.class
class samCommand2 implements command{
  public void s(){System.out.println("command2");}
}
commandPool.class
class commandPool{
  command[] pool=new command[2];  // command.interfaceを実装したクラスインスタンスを格納します
  void set(int key,command com){
    if(pool[key]==null){
       pool[key]=com;
    }
  }
  void exec(int key){
    pool[key].s();
  }
}
user(Main.class)
public static void main(String[] args){
  samCommand1 sc1 = new samCommand1();
  samCommand2 sc2 = new samCommand2();
  commandPool cop = new commandPool();
  cop.set(0,sc1);
  cop.set(1,sc2);
  cop.exec(1);
}}

メソッド実行回数を表示する機能の追加

commandPool.classを下記に修正

commandPool.class
class commandPool{
  command[] pool = new command[4];
  int[] count = new int[2];
  void  set(int key,command com){
    if(pool [key]==null){
       pool [key]=com;
       count[key]=0;
    }
  }
  void exec(int key){
    pool [key].s();
    count[key]++;
    System.out.println(count[key]+"回目");
  }
}
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