宮女類(接受者):java
package designpattern.command; /* * 宮女 */ public class Maid { String name; public Maid(String name) { this.name = name; } public void clean() { System.out.println(this.name + ":打掃衛生"); } }
太監類(接受者):ide
package designpattern.command; /* * 太監 */ public class Eunuch { String name; public Eunuch(String name) { this.name = name; } public void carrySedanChair() { System.out.println(this.name + ":擡轎子"); } }
抽象命令接口:ui
package designpattern.command; public interface Command { public void execute(); }
打掃命令類(具體命令類):this
package designpattern.command; public class CleanCommand implements Command { private Maid maid; public CleanCommand(Maid maid) { this.maid = maid; } @Override public void execute() { maid.clean(); } }
擡轎子命令類(具體命令類):spa
package designpattern.command; public class CarrySedanChairCommand implements Command { private Eunuch eunuch; public CarrySedanChairCommand(Eunuch eunuch) { this.eunuch = eunuch; } @Override public void execute() { eunuch.carrySedanChair(); } }
太監總管類(Invoker):設計
package designpattern.command; import java.util.ArrayList; import java.util.List; public class ManagerEunuch { private List<Command> commands = new ArrayList<Command>(); public void setCommand(Command command) { this.commands.add(command); } public void notifyIt() { for (Command command : commands) { command.execute(); } } }
客戶端:日誌
package designpattern.command; public class Client { public static void main(String[] args) { Maid xiaocui = new Maid("小翠"); Maid xiaohua = new Maid("小花"); Eunuch xiaozhuozi = new Eunuch("小卓子"); Eunuch xiaoguizi = new Eunuch("小貴子"); Command cleanCommand1 = new CleanCommand(xiaocui); Command cleanCommand2 = new CleanCommand(xiaohua); Command carrySedanChairCommand1 = new CarrySedanChairCommand(xiaozhuozi); Command carrySedanChairCommand2 = new CarrySedanChairCommand(xiaoguizi); ManagerEunuch ligongong = new ManagerEunuch(); ligongong.setCommand(cleanCommand1); ligongong.setCommand(cleanCommand2); ligongong.setCommand(carrySedanChairCommand1); ligongong.setCommand(carrySedanChairCommand2); ligongong.notifyIt(); } }
結果輸出:code
小翠:打掃衛生
小花:打掃衛生
小卓子:擡轎子
小貴子:擡轎子