• 状态模式的另一种写法


    <?php
    /**
     * 状态模式
     * 允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它所属的类
     */
    
    /*接口*/
    interface State
    {
        public function handle($state);//切换到下一个状态
        public function display();//显示当前状态
    }
    
    /*状态A*/
    class StateA implements State
    {
        public function handle($context)
        {
            $context->setState(new StateB());
        }
    
        public function display()
        {
            echo "state A<br />";
        }
    }
    /*状态B*/
    class StateB implements State
    {
        public function handle($context)
        {
            $context->setState(new StateC());
        }
    
        public function display()
        {
            echo "state B<br/>";
        }
    }
    /*状态C*/
    class StateC implements State
    {
        public function handle($context)
        {
            $context->setState(new StateA());
        }
    
        public function display()
        {
            echo "state C<br/>";
        }
    }
    
    
    class Context
    {
        private $_state = null;
        public function __construct($state)//给初始状态
        {
            $this->setState($state);
        }
    
        public function setState($state)//设置状态的函数
        {
            $this->_state = $state;
        }
    
        public function request()//执行显示状态并切换状态
        {
            $this->_state->display();
            $this->_state->handle($this);
        }
    }
    
    // 实例化一下
    $objContext = new Context(new StateB());
    $objContext->request();
    $objContext->request();
    $objContext->request();
    $objContext->request();
    $objContext->request();
    ?>
  • 相关阅读:
    Spring + SpringMVC + MyBatis
    jquery+bootstrap使用数字增减按钮
    Eclipse添加代码注释模板
    No goals have been specified for this build
    字符串前面自动补零
    深入理解JavaScript系列
    java判断A字符串是否包含B字符串
    WebSocket 实战
    button点击切换,获取按钮ID
    JS 中判断空值 undefined 和 null
  • 原文地址:https://www.cnblogs.com/jiufen/p/5026314.html
Copyright © 2020-2023  润新知