标签:
Command: 抽象命令类
ConcreteCommand: 具体命令类
Invoker: 调用者
Receiver: 接收者
Client:客户类
优点
1. 降低了系统耦合度
2. 新的命令可以很容易添加到系统中去。
缺点
使用命令模式可能会导致某些系统有过多的具体命令类。
Traders.java
package com.soyoungboy.command1; public class Traders { /** * @Title: sailMineralWater * @Description: TODO(卖矿泉水) * @param 设定文件 * @return void 返回类型 * @throws */ public void sailMineralWater() { System.out.println("卖矿泉水"); } /** * @Title: sailIceBlackTea * @Description: TODO(卖冰紅茶) * @param 设定文件 * @return void 返回类型 * @throws */ public void sailIceBlackTea() { System.out.println("卖冰紅茶"); } }
/** * @ClassName: Command * @Description: TODO(抽象命令类) */ public abstract class Command { private Traders traders; public Command(Traders traders) { this.traders = traders; } /** * @return 返回 traders **/ public Traders getTraders() { return traders; } /** * @param traders 要设置的 traders */ public void setTraders(Traders traders) { this.traders = traders; } public abstract void sail(); }
package com.soyoungboy.command1; /** * * @ClassName: MineralWaterCommand * @Description: TODO(具体命令类 --販賣礦泉水) */ public class MineralWaterCommand extends Command { public MineralWaterCommand(Traders traders) { super(traders); } @Override public void sail() { this.getTraders().sailMineralWater(); } }
package com.soyoungboy.command1; /** * * @ClassName: IceBlackTeaCommand * @Description: TODO(具体命令类 --販賣冰紅茶) */ public class IceBlackTeaCommand extends Command { public IceBlackTeaCommand(Traders traders) { super(traders); } @Override public void sail() { this.getTraders().sailIceBlackTea(); } }
package com.soyoungboy.command1; import java.util.ArrayList; /** * @ClassName: Cashier * @Description: TODO(接收者 -- 收銀員類) */ public class Cashier { public ArrayList<Command> drinks = new ArrayList<Command>(); /** * @Title: addDrinks * @Description: TODO(购买各种饮料) * @param @param command 设定文件 * @return void 返回类型 * @throws */ public void addDrinks(Command command) { drinks.add(command); } /** * @Title: removeDrinks * @Description: TODO(不要某種飲料) * @param @param command 设定文件 * @return void 返回类型 * @throws */ public void removeDrinks(Command command) { drinks.remove(command); } /** * @Title: sail * @Description: TODO(售卖各自的饮料) * @param 设定文件 * @return void 返回类型 * @throws */ public void sail() { for (Command drink : drinks) { drink.sail(); } } }
package com.soyoungboy.command1; public class Test { public static void main(String[] args) { Cashier cashier = new Cashier(); Traders traders = new Traders(); MineralWaterCommand mineralWaterCommand = new MineralWaterCommand(traders); IceBlackTeaCommand iceBlackTeaCommand = new IceBlackTeaCommand(traders); //来瓶冰红茶和矿泉水 cashier.addDrinks(mineralWaterCommand); cashier.addDrinks(iceBlackTeaCommand); cashier.sail(); System.out.println("----------------"); //再来瓶冰红茶 cashier.addDrinks(iceBlackTeaCommand); cashier.sail(); System.out.println("----------------"); //不要一瓶矿泉水了 cashier.removeDrinks(mineralWaterCommand); cashier.sail(); } }
标签:
原文地址:http://www.cnblogs.com/androidsuperman/p/4853974.html