1. 程式人生 > >設計模式:命令模式(Command Pattern)

設計模式:命令模式(Command Pattern)

/**
 * 命令模式。
 * @author Bright Lee
 */
public class CommandPattern {

	public static void main(String[] args) {
		Receiver receiver = new Receiver();
		
		Command cmd001 = new OnCommand(receiver);
		Command cmd002 = new OffCommand(receiver);
		
		Invoker invoker = new Invoker();
		
		invoker.setCommand(cmd001);
		// 這個呼叫者持有一個命令物件,在某個時間點呼叫
		// 命令物件的execute()方法,將請求付諸實施:
		invoker.invoke();
		
		invoker.setCommand(cmd002);
		invoker.invoke();
	}

}

/**
 * 接收者。負責執行具體的業務邏輯,所有的物件都可以成為接收者。
 */
class Receiver {
	
	public void on() {
		System.out.println("開啟。");
	}
	
	public void off() {
		System.out.println("關閉。");
	}
	
}

/**
 * 命令介面。
 */
interface Command {
	
	public void execute();
	
}

/**
 * 開命令。
 */
class OnCommand implements Command {

	private Receiver receiver;
	
	public OnCommand(Receiver receiver) {
		this.receiver = receiver;
	}
	
	public void execute() {
		receiver.on();
	}
	
}

/**
 * 關命令。
 */
class OffCommand implements Command {

	private Receiver receiver;
	
	public OffCommand(Receiver receiver) {
		this.receiver = receiver;
	}
	
	public void execute() {
		receiver.off();
	}
	
}

/**
 * 呼叫者。
 */
class Invoker {
	
	private Command command;
	
	public void setCommand(Command command) {
		this.command = command;
	}
	
	public void invoke() {
		command.execute();
	}
	
}

執行結果:
開啟。
關閉。