装饰器模式
2015-08-31 10:42
471 查看
定义:装饰器模式可以动态的添加修改类的功能
初始的一个类,无任何修饰,只简单的输出helloworld<? class HelloWorld { protected $output="HelloWorld"; public function output() { echo $this->output; } } $hw=new HelloWorld(); $hw->output();
现在运用装饰期模式来给来给该类的输出增加颜色,代码如下
<?php /** * * @authors mtg * @date 2015-08-31 09:45:01 */ /*此处的作用是 *定义一个装饰器接口 */ interface Decorator{ function before_method(); function after_method(); } /*此处的作用是 *定义一个颜色装饰器 */ class ColorDecorator implements Decorator{ protected $color; function __construct($value='') { $this->color=$value; } public function before_method() { echo "<div style='color:".$this->color."'>"; } public function after_method() { echo "</div>"; } } class HelloWorld { protected $decorator=array(); protected $output="HelloWorld"; public function addDecorator(Decorator $decorator) { $this->decorator[]=$decorator; } public function output() { $this->before_op(); echo $this->output; $this->after_op(); } public function before_op(){ if (!empty($this->decorator)) { foreach ($this->decorator as $key => $value) { $value->before_method(); } } } public function after_op() { /*此处的作用是 *需要将装饰器倒序后再调用方法 */ if (!empty($this->decorator)) { $this->decorator=array_reverse($this->decorator); foreach ($this->decorator as $key => $value) { $value->after_method(); } } } } $hw=new HelloWorld(); $hw->output(); $colordecorator=new ColorDecorator('red'); $hw->addDecorator($colordecorator); $hw->output();
相关文章推荐
- Tomcat启动找不到JRE_HOME的解决方法
- yii2系统定义的常用路径别名
- eclipse配置Tomcat服务器Server Locations,可以配置web项目自动部署到tomcat
- B\S备忘录27——EF强行多租户效果?是在下输了
- (4.1.35)Android捕获全局异常信息并实现上传
- SDUTOJ 3309乱七八糟的图(spfa)
- 显卡的相关性能参数含义(struct cudaDeviceProp)
- Spring.NET程序
- Genymotion中SD卡目录在Eclipse中查看,以及创建SDCard
- excel 读取模板,病写入新文件
- 用ps污点画笔修复工具讲图片变成朦胧效果
- 1039. Course List for Student (25)
- VS试用版的评估期XX天后结束及找不到输入序列号的地方
- 使用Axure RP原型设计实践06,登录验证
- 登录远程服务器抓包
- 边框的css3样式
- 【Leetcode】【Hard】Merge Intervals
- 关于CornerStone配置SVN简单使用
- overflow:hidden
- 基于C++11 thread 实现线程池