• B3:状态模式 State


    当一个对象内在状态改变时允许改变其行为,这个对象看起来像是改变了其类.
    状态模式主要解决当控制一个对象状态转换条件表达式过于复杂时的情况,把状态判断逻辑移到表示不同状态的一系列类中.如果状态判断很简单,就没有必要用这个模式了.

    1.相当于面向过程中的if/else,状态模式在每个独立的状态类中实现判断,符合则处理,不符合则交给下一个状态类.

    2.内部状态改变时,行为变化剧烈

    3.有一个内部状态

    UML

    示例代码:

    interface StateInterface
    {
        public function handle(Context $context);
    }
    
    class StateA implements StateInterface
    {
        public function handle(Context $context)
        {
            if ($context->getTime() == 'AM') {
                echo '这是早晨';
                echo 'Action: 写入日志';
            } else {
                $context->setState(new StateB());
                $context->handle();
            }
        }
    }
    
    class StateB  implements StateInterface
    {
        public function handle(Context $context)
        {
            if ($context->getTime() == 'PM') {
                echo '这是下午';
                echo 'Action: 显示界面';
            } else {
                $context->setState(new StateA());
                $context->handle();
            }
        }
    }
    
    class Context
    {
        protected $time;
        protected $state;
    
        public function __construct()
        {
            $this->state = new StateA();
        }
    
        public function setTime($time)
        {
            $this->time = $time;
        }
    
        public function getTime()
        {
            return $this->time;
        }
    
        public function setState(StateInterface $state)
        {
            $this->state = $state;
        }
    
        public function handle()
        {
            return $this->state->handle($this);
        }
    }
    
    $state = new Context();
    $state->setTime('PM');
    $state->handle();
    

      

  • 相关阅读:
    Ubuntu ctrl+alt会导致窗口还原的问题
    Ubuntu设置显示桌面快捷键
    ubuntu鼠标和触摸板的禁用
    Codeforces Round #271 (Div. 2) F题 Ant colony(线段树)
    友盟社会化分享
    ZOJ 3890 Wumpus
    九种迹象表明你该用Linux了
    Java集合源代码剖析(二)【HashMap、Hashtable】
    01_GIT基础、安装
    Launcher知识的demo,手机管家小伙家与悬浮窗
  • 原文地址:https://www.cnblogs.com/itfenqing/p/7788755.html
Copyright © 2020-2023  润新知