分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

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

发布时间:2023-09-06 01:59责任编辑:胡小海关键词:PHP
github地址:https://github.com/ZQCard/design_pattern
/** * 在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。 * 在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。 * 对象的行为依赖于它的状态(属性),并且可以根据它的状态改变而改变它的相关行为。 */

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

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

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

<?phpnamespace 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(具体的开始状态类)

<?phpnamespace 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(具体的结束状态类)

<?phpnamespace 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(客户端类)

<?phpspl_autoload_register(function ($className){ ???$className = str_replace(‘\\‘,‘/‘,$className); ???include $className.".class.php";});use State\Context;use State\StartState;use State\StopState;$context = new ?Context();$startState = new StartState();$startState->doAction($context);$context->getState()->handle();$startState = new StopState();$startState->doAction($context);$context->getState()->handle();

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

原文地址:https://www.cnblogs.com/zhouqi666/p/9164932.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved