美文网首页
命令模式

命令模式

作者: simplerandom | 来源:发表于2020-05-20 11:20 被阅读0次

    命令接口
    命令具体类
    命令接收者
    命令发送者

    public interface Command {
        void turnOff();
        void turnOn();
    
    }
    
    public class TurnOnCommand implements Command {
        Light light;
    
        public TurnOnCommand(Light light) {
            this.light = light;
        }
    
    
        @Override
        public void turnOff() {
            light.turnOff();
        }
    
        @Override
        public void turnOn() {
            light.turnOn();
        }
    }
    
    
    public class Light {
        public void turnOn(){
            System.out.println("开灯");
        }
        public void turnOff(){
            System.out.println("关灯");
        }
    }
    
    public class Actor {
        Command command;
    
        public Actor(Command command) {
            this.command = command;
        }
        public void executeTurnOn(){
            command.turnOn();
        }
        public void executeTurnOff(){
            command.turnOff();
        }
    }
    
    

    测试

    public class Test {
        public static void main(String[] args) {
            Actor actor = new Actor(new TurnOnCommand(new Light()));
            actor.executeTurnOn();
            actor.executeTurnOff();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:命令模式

          本文链接:https://www.haomeiwen.com/subject/njygohtx.html