command - 對象行爲型模式

       1.意圖
        將一個請求封裝爲一個對象,從而使你可以用不同的請求對客戶進行參數化;對請求
        排隊或者記錄請求日誌以及支持可撤銷的操作
        2.參與者
        Command - 聲明執行操作的接口
        ConcreteCommand -將一個接收者對象綁定於一個對象
                        -調用接收者相應的操作以實現Execute
        Client  - 創建一個具體命令對象並設定它的接收者
        Invoker - 要求該命令執行這個請求
        Receiver - 知道如何實施與執行一個請求相關操作

        3.結構

4.代碼

public interface Command {
  void execute();
}

public class NullCommand implements Command {

	@Override
	public void execute() {

	}

}

public class ConcreteCommandA implements Command {
	LightReceiver L;
	ConcreteCommandA(LightReceiver L){
		this.L = L;
	}
	@Override
	public void execute() {
		L.turnOff();

	}

}

public class ConcreteCommandB implements Command {
	LightReceiver L;
	ConcreteCommandB(LightReceiver L){
		this.L = L;
	}
	@Override
	public void execute() {
		L.turnOn();

	}

}

public class LightReceiver {
   public void turnOn(){
 	System.out.println("開燈");
  }
   public void turnOff(){
	System.out.println("關燈");
   }
}

public class Invoker {
	Command command = new NullCommand();

	public void setCommand(Command command) {
		this.command = command;
	}

	public void action() {
		command.execute();
	}

public class Client {
  public static void main(String[] args) {
	  LightReceiver lr = new LightReceiver();
	  ConcreteCommandA a = new ConcreteCommandA(lr);
	  ConcreteCommandB b = new ConcreteCommandB(lr);
	  Invoker invoker = new Invoker();
	  invoker.setCommand(a);
	  invoker.action();
	  invoker.setCommand(b);
	  invoker.action();
}
}

 

 




 

 

 

 

 

 



 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章