设计模式之状态设计模式

  • 什么是状态设计模式
    状态设计模式的作用是允许对象在状态改变时,改变其行为。如游戏中经常用到状态设计模式,因为游戏中的对象往往会非常频繁的改变状态
  • 何时使用状态设计模式
    一个对象依赖于它的状态时,它肯定会频繁的改变,这种情况下,有状态设计模式既有绝对的优势

下面的示例代码是利用状态设计模式实现电灯的开灯和关灯。

<?php

class Context {

    private $offState;
    private $onState;
    private $currentstate;

    public function __construct() {
        $this->offState = new OffState($this);
        $this->onState = new OnState($this);
        $this->currentstate = $this->offState;
    }

    public function turnOnLight() {
        $this->currentstate->turnLightOn();
    }

    public function turnOffLight() {
        $this->currentstate->turnLightOff();
    }

    public function setState(IState $state) {
        $this->currentstate = $state;
    }

    public function getOnState() {
        return $this->onState;
    }

    public function getOffState() {
        return $this->offState;
    }

}

interface IState {

    public function turnLightOn();

    public function turnLightOff();
}

class OnState implements IState {

    private $context;

    function __construct(Context $context) {
        $this->context = $context;
    }

    public function turnLightOn() {
        echo "the light is already on->take no action<br>";
    }

    public function turnLightOff() {
        echo "Lights Off!!<br />";
        $this->context->setState($this->context->getOffState());
    }

}

class OffState implements IState {

    private $context;

    function __construct(Context $context) {
        $this->context = $context;
    }

    public function turnLightOn() {
        echo "Lights On!!<br />";
        $this->context->setState($this->context->getOnState());
    }

    public function turnLightOff() {
        echo "the light is already off->take no action<br>";
    }

}

class client {

    private $context;

    public function __construct() {
        $this->context = new Context();//context对象作为一个参与者,来跟踪状态对象所处的状态
        $this->context->turnOffLight(); 
        $this->context->turnOnLight();
        $this->context->turnOnLight();
        $this->context->turnOffLight();
        $this->context->turnOffLight();
    }

}

new client();

the light is already off->take no action
Lights On!!
the light is already on->take no action
Lights Off!!
the light is already off->take no action

  • 总结
    状态设计模式是模拟器和游戏的主要方法,其实不局限与此,只要php程序的用户会用到一组有限的状态,开发人员就可以使用状态设计模式
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值