大话设计模式-命令模式的实践-烤羊肉串

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();

    }
}

运行结果

烤鸡翅
烤羊肉串

全部评论

相关推荐

我已成为0offer的糕手:别惯着,胆子都是练出来的,这里认怂了,那以后被裁应届被拖工资还敢抗争?
点赞 评论 收藏
分享
11-02 09:49
已编辑
货拉拉_测试(实习员工)
热爱生活的仰泳鲈鱼求你们别卷了:没事楼主,有反转查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务