zoukankan      html  css  js  c++  java
  • 一天一个设计模式(13)——命令模式

    <?php
    class Bulb {
        public function turnOn() {
            echo 'Bulb has turned on';
        }
    
        public function turnOff() {
            echo 'Bulb has turned off';
        }
    }
    
    interface Order {
        public function execute();
        public function undo();
        public function redo();
    }
    
    class TurnOn implements Order {
        private $_bulb;
        public function __construct(Bulb $bulb) {
            $this->_bulb = $bulb;
        }
    
        public function execute() {
            $this->_bulb->turnOn();
        }
    
        public function undo() {
            $this->_bulb->turnOff();
        }
    
        public function redo() {
            $this->_bulb->turnOn();
        }
    }
    
    class TurnOff implements Order {
        private $_bulb;
    
        public function __construct($bulb) {
            $this->_bulb = $bulb;
        }
    
        public function execute() {
            $this->_bulb->turnOff();
        }
    
        public function undo() {
            $this->_bulb->turnOn();
        }
    
        public function redo() {
            $this->_bulb->turnOff();
        }
    }
    
    class Control {
        public function submit($order) {
            $order->execute();
        }
    }
    
    $bulb = new Bulb();
    $turnOn = new TurnOn($bulb);
    $turnOff = new TurnOff($bulb);
    
    $control = new Control();
    $control->submit($turnOn);
    echo PHP_EOL;
    $control->submit($turnOff);

    本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/7203962.html

  • 相关阅读:
    S3:代理模式 Proxy
    S2:外观模式 Facade
    S1:适配器 Adapter
    C5:单例模式 Singleton
    C4:原型模式 Prototype
    C3:建造者模式 Builder
    C2:抽象工厂 Abstract Factory
    C1:工厂模式 Factory
    设计模式分类
    数据访问对象模式
  • 原文地址:https://www.cnblogs.com/Bin-x/p/7203962.html
Copyright © 2011-2022 走看看