大话设计模式-命令模式的实践-烤羊肉串
UML
抽象命令类
/** * @ClassName: Command * @Author: Leo * @Description: 抽象命令类 * @Date: 2019/5/21 9:54 */
public abstract class Command {
protected Barbecuer barbecuer;
public Command(Barbecuer barbecuer) {
this.barbecuer = barbecuer;
}
/** * 执行命令 */
public abstract void excuteCommand();
}
烤鸡翅命令
/** * @ClassName: BakeChickenCommand * @Author: Leo * @Description: 烤鸡翅命令 * @Date: 2019/5/21 10:01 */
public class BakeChickenCommand extends Command {
public BakeChickenCommand(Barbecuer barbecuer) {
super(barbecuer);
}
@Override
public void excuteCommand() {
barbecuer.bakeChickenWing();
}
}
烤羊肉命令
/** * @ClassName: BakeMuttonCommand * @Author: Leo * @Description: 烤羊肉命令 * @Date: 2019/5/21 10:00 */
public class BakeMuttonCommand extends Command {
public BakeMuttonCommand(Barbecuer barbecuer) {
super(barbecuer);
}
@Override
public void excuteCommand() {
barbecuer.bakeMutton();
}
}
烤肉串者
/** * @ClassName: Barbecuer * @Author: Leo * @Description: 烤肉串者 * @Date: 2019/5/21 9:54 */
public class Barbecuer {
/** * 烤羊肉串 */
public void bakeMutton() {
System.out.println("烤羊肉串");
}
/** * 烤鸡翅 */
public void bakeChickenWing() {
System.out.println("烤鸡翅");
}
}
服务员类
import java.util.ArrayList;
import java.util.List;
/** * @ClassName: Waiter * @Author: Leo * @Description: 服务员类 * @Date: 2019/5/21 10:01 */
public class Waiter {
private List<Command> commands = new ArrayList<>();
/** * 添加订单 * * @param command */
public void setCommand(Command command) {
commands.add(command);
}
/** * 取消订单 * * @param command */
public void cancelOrder(Command command) {
commands.remove(command);
}
/** * 通知烤肉的人去执行命令 */
public void Notify() {
for (Command command : commands) {
command.excuteCommand();
}
}
}
测试类
/** * @ClassName: Main * @Author: Leo * @Description: 测试类 * @Date: 2019/5/21 9:37 */
public class Main {
public static void main(String[] args) {
Barbecuer barbecuer = new Barbecuer();
Command command1 = new BakeChickenCommand(barbecuer);
Command command2 = new BakeMuttonCommand(barbecuer);
Waiter waiter = new Waiter();
waiter.setCommand(command1);
waiter.setCommand(command2);
waiter.Notify();
}
}
运行结果
烤鸡翅
烤羊肉串