• 设计模式之状态模式(PHP实现)


    github地址:https://github.com/ZQCard/design_pattern
    /**
     * 在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。
     * 在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。
     * 对象的行为依赖于它的状态(属性),并且可以根据它的状态改变而改变它的相关行为。
     */

    (1)State.class.php(接口,规定实现方法)

    <?php
    
    namespace State;
    
    interface State
    {
        public function doAction(Context $context);
    }

    (2)Context.class.php (带有某个状态的类)

    <?php
    
    namespace State;
    
    class Context
    {
        private $state;
    
        public function __construct()
        {
            $this->state = null;
        }
    
        public function setState(State $state)
        {
            $this->state = $state;
        }
    
        public function getState()
        {
            return $this->state;
        }
    }

    (3)StartState.class.php(具体的开始状态类)

    <?php
    
    namespace State;
    
    class Context
    {
        private $state;
    
        public function __construct()
        {
            $this->state = null;
        }
    
        public function setState(State $state)
        {
            $this->state = $state;
        }
    
        public function getState()
        {
            return $this->state;
        }
    }

    (4)StopState.class.php(具体的结束状态类)

    <?php
    
    namespace State;
    
    class StopState implements State
    {
        public function doAction(Context $context)
        {
            echo "Player is in stop state";
            $context->setState($this);
        }
    
    
        public function handle()
        {
            return 'stop state';
        }
    }

    (5)state.php(客户端类)

    <?php
    
    spl_autoload_register(function ($className){
        $className = str_replace('\','/',$className);
        include $className.".class.php";
    });
    
    use StateContext;
    use StateStartState;
    use StateStopState;
    
    $context = new  Context();
    
    $startState = new StartState();
    $startState->doAction($context);
    $context->getState()->handle();
    
    $startState = new StopState();
    $startState->doAction($context);
    $context->getState()->handle();
  • 相关阅读:
    两数之和
    swift 结构体
    打家劫舍II
    Swift的访问控制讲解
    swift版 二分查找 (折半查找)
    RAC(ReactiveCocoa)介绍(一)
    变位词
    双向循环链表
    单链表
    顺序链表(C++)
  • 原文地址:https://www.cnblogs.com/zhouqi666/p/9164932.html
Copyright © 2020-2023  润新知