zoukankan      html  css  js  c++  java
  • 设计模式之状态模式(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();
  • 相关阅读:
    P5047 [Ynoi2019 模拟赛] Yuno loves sqrt technology II
    P4887 【模板】莫队二次离线(第十四分块(前体))
    SP20644 ZQUERY
    企业战略管理【0612】
    管理经济学【0812】
    商务沟通[0664]
    国际企业管理【0813】
    社区管理【0272】
    战略管理【1059】
    管理沟通【1279】
  • 原文地址:https://www.cnblogs.com/zhouqi666/p/9164932.html
Copyright © 2011-2022 走看看