定义
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构,属于结构型模式。
代码实例
现有编辑器接口有写代码(write)的功能,现在要扩展写的功能,加入转换编码格式的功能,在不修改原有对象的情况下,通过一个抽象类实现编辑器的接口,再由抽象类的具体类实现对转换编码格式功能的扩展。
<?php
<?php
namespace decorator;
interface Editor
{
public function write();
}
class Phpstorm implements Editor
{
public function write()
{
echo 'phpstorm 写代码很爽';
}
}
class Notepad implements Editor
{
public function write()
{
echo 'notepad 写代码考验白板能力';
}
}
abstract class EditorDecorator implements Editor
{
protected $editor;
public function __construct($editor)
{
$this->editor = $editor;
}
public function convertCoding()
{
echo '现在增加转换代码的操作';
}
abstract public function write();
}
class CodingEditorDecorator extends EditorDecorator
{
public function write()
{
$editor_write = $this->editor->write();
echo $editor_write . '<br>' . $this->convertCoding();
}
}
class DecoratorDemo
{
public function handle()
{
$codingEditor_phpstorm = new CodingEditorDecorator(new Phpstorm());
$codingEditor_notepad = new CodingEditorDecorator(new Notepad());
$codingEditor_phpstorm->write();
$codingEditor_notepad->write();
}
}
$decoratorDemo = new DecoratorDemo();
$decoratorDemo->handle();
总结
装饰器模式用于动态的修改对象,可以灵活添加和删除对象的功能,从而避免子类继承的过度臃肿,多层装饰会不利于代码的阅读。
网友评论