liguofeng29’s blog

個人勉強用ブログだっす。

デザインパターン - Command

【Commandパターンとは】

要求自体をオブジェクトにしてしまい、そのオブジェクトを引数に渡す。

Commandパターンのクラス図】

 

Commandパターンのメリット】

さまざまな要求を送ろうとすると、引数の数や種類を増やさなければなりませんが、

それには限界がある。

 

【サンプル】

TV.java
package command;
 
// TV
public class TV {
    public void on() {
        System.out.println("TVをONにしました。");
    }
 
    public void off() {
        System.out.println("TVをOFFにしました。");
    }
}
 
 
 
 

 

RemoteControl.java
package command;
 
// リモコン
public class RemoteControl {
 
    Command commands;
 
    public RemoteControl() {
        // ボタン2つ
        this.commands = new Command[2];
    }
 
    public void addCommand(int slot, Command command) {
        if(slot != 0 || slot != 1){
            // コマンド設定
            this.commands[slot] = command;
        }
    }
 
    // リモコンを押す
    public void push(int slot) {
        this.commands[slot].execute();
    }
}
 
 

 

Command.java
package command;
 
// コマンドIF
public interface Command {
    public void execute();
}
 
 
 
 
 

 

OnCommand.java
package command;
 
// 電源ONコマンド
public class OnCommand implements Command{
 
    private TV tv;
 
    public OnCommand(TV tv) {
        this.tv = tv;
    }
 
    @Override
    public void execute() {
        this.tv.on();
    }
 
}
 
 
 
 

 

OffCommand.java
package command;
 
// 電源OFFコマンド
public class OffCommand implements Command{
 
    private TV tv;
 
    public OffCommand(TV tv) {
        this.tv = tv;
    }
 
    @Override
    public void execute() {
        this.tv.off();
    }
 
}
 
 
 
 

 

Person.java
package command;
 
public class Person {
 
    /**
     * @param args
     */
    public static void main(String args) {
 
        // TV
        TV tv = new TV();
 
        // リモコン
        RemoteControl remoteControl = new RemoteControl();
 
        // コマンド
        Command on = new OnCommand(tv);
        Command off = new OffCommand(tv);
 
        // コマンド設定
        remoteControl.addCommand(0, on);
        remoteControl.addCommand(1, off);
 
        // リモコン0を押す
        remoteControl.push(0);
        // リモコン1を押す
        remoteControl.push(1);
    }
}
 
 
 
 
実行結果
TVをONにしました。
TVをOFFにしました。