设计模式-行为型-命令模式


import java.util.ArrayList;
import java.util.List;

/**
 * 命令模式
 * 类型: 行为型
 * 描述: 将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持撤销和恢复功能
 */
public class CommandMode {

    // 命令接收者
    public static class Receiver {
        public void action() {
            System.out.println("Receiver action");
        }
    }

    // 命令
    public static class ConcreteCommand implements Command {
        private Receiver receiver;

        public ConcreteCommand(Receiver receiver) {
            this.receiver = receiver;
        }

        public void execute() {
            receiver.action();
        }
    }

    // 命令接口
    public static interface Command {
        void execute();
    }

    // 接收者接口
    public interface LightReceiver {
        void turnOn();
        void turnOff();
    }

    public static class LightOnCommand implements Command {
        private LightReceiver lightReceiver;

        public LightOnCommand(LightReceiver lightReceiver) {
            this.lightReceiver = lightReceiver;
        }

        @Override
        public void execute() {
            lightReceiver.turnOn();
        }
    }

    public static class LightOffCommand implements Command {
        private LightReceiver lightReceiver;

        public LightOffCommand(LightReceiver lightReceiver) {
            this.lightReceiver = lightReceiver;
        }

        @Override
        public void execute() {
            lightReceiver.turnOff();
        }
    }

    // 具体接收者类
    public static class SimpleLight implements LightReceiver {
        @Override
        public void turnOn() {
            System.out.println("Light is on.");
        }

        @Override
        public void turnOff() {
            System.out.println("Light is off.");
        }
    }

    // 调用者
    public static class RemoteControl {
        private List<Command> commands = new ArrayList<>();

        public void setCommand(int slot, Command command) {
            commands.set(slot, command);
        }

        public void pressButton(int slot) {
            commands.get(slot).execute();
        }
    }



    // 命令调用者
    public static class Invoker {
        private Command command;

        public Invoker(Command command) {
            this.command = command;
        }

        public void action() {
            command.execute();
        }
    }

    public static void main(String[] args) {
        // 创建接收者
        Receiver receiver = new Receiver();
        // 创建命令
        Command command = new ConcreteCommand(receiver);
        // 创建调用者
        Invoker invoker = new Invoker(command);
        // 执行命令
        invoker.action();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值