加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php状态模式(state pattern)

发布时间:2020-12-13 16:07:46 所属栏目:PHP教程 来源:网络整理
导读:... ? php /* The state pattern encapsulates the varying behavior for the same object based on itsinternal state,making an object appear as if it has changed its class. */ interface Statelike { public function writeName(StateContext $contex

...

<?php
/*
The state pattern encapsulates the varying behavior for the same object based on its
internal state,making an object appear as if it has changed its class.
*/

interface  Statelike {
    public function writeName(StateContext $context,$name);
}

class StateLowerCase implements Statelike {
    public function writeName(StateContext $context,$name) {
        echo strtolower($name);
        $context->setState(new StateMultileUpperCase());
    }
}

class StateMultileUpperCase implements Statelike {
    private $count = 0;
    
    public function writeName(StateContext $context,$name) {
        $this->count++;
        echo strtoupper($name);
        
        if ($this->count > 1) {
            $context->setState(new StateLowerCase());
        }
    }
}

class StateContext {
    private $state;
    
    public function setState(Statelike $state) {
        $this->state = $state;
    }
    
    public function writeName($name) {
        $this->state->writeName($this,$name);
    }
}

$stateContext = new StateContext();
$stateContext->setState(new StateLowerCase());
$stateContext->writeName(‘Monday<br/>‘);
$stateContext->writeName(‘TuesDay<br/>‘);
$stateContext->writeName(‘Wednesday<br/>‘);
$stateContext->writeName(‘Thursday<br/>‘);
$stateContext->writeName(‘Friday<br/>‘);
$stateContext->writeName(‘Saturday<br/>‘);
$stateContext->writeName(‘Sunday<br/>‘);

?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读