package com.maom.design.D_24_Command;
import java.util.ArrayList;
import java.util.List;
/**
* @Title: D_24_Command
* @Description: 24_命令模式
* @Author maohb
* @Version 1.0
*/
public class D_24_Command {
public static void main(String[] args) {
Peddler peddler = new Peddler();
// peddler.sailApple();
// peddler.sailBanana();
Command appleCommand = new AppleCommand(peddler);
Command bananaCommand = new BananaCommand(peddler);
// appleCommand.sail();
// bananaCommand.sail();
//下订单
Waiter waiter = new Waiter();
waiter.setOrder(appleCommand);
waiter.setOrder(bananaCommand);
//移除订单某项
waiter.removeOrder(appleCommand);
// 执行
waiter.sail();
}
}
/** 小商贩 */
class Peddler {
public void sailApple() {
System.out.println("卖苹果");
}
public void sailBanana() {
System.out.println("卖香蕉");
}
}
/** 命令抽象类 */
abstract class Command {
private Peddler peddler;
public Command(Peddler peddler) {
this.peddler = peddler;
}
public Peddler getPeddler() {
return peddler;
}
public void setPeddler(Peddler peddler) {
this.peddler = peddler;
}
public abstract void sail();
}
/** 命令具体实现类 - 苹果 */
class AppleCommand extends Command {
public AppleCommand(Peddler peddler) {
super(peddler);
}
public void sail() {
this.getPeddler().sailApple();
}
}
/** 命令具体实现类 - 香蕉 */
class BananaCommand extends Command{
public BananaCommand(Peddler peddler) {
super(peddler);
}
public void sail() {
this.getPeddler().sailBanana();
}
}
/** 调用者 invoker */
class Waiter {
// 菜单列表
private List<Command> commands = new ArrayList<Command>();
// 菜单操作
public void setOrder(Command command) {
commands.add(command);
}
public void removeOrder(Command command) {
commands.remove(command);
}
// 循环调用菜单
public void sail() {
commands.stream().forEach(command -> command.sail());
}
}
设计模式笔记_24_命令模式
最新推荐文章于 2024-09-10 17:07:09 发布