PHP设计模式装饰器模式

WBOY
發布: 2016-06-20 12:40:48
原創
981 人瀏覽過

装饰器设计模式

什么是装饰器模式

装饰器模式就是对一个已有的结构增加装饰。装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

何时使用装饰器

基本说来, 如果想为现有对象增加新功能而不想影响其他对象, 就可以使用装饰器模式.

装饰器类图

装饰器的组成

  1. Component接口:定义一个对象接口,以规范准备接受附加责任的对象。
  2. Decorator接口:装饰器接口
  3. ConcreteComponent :具体组件角色,即将要被装饰增加功能的类
  4. ConcreteDecorator :具体装饰器,向组件添加职责

代码

Component接口

<?php namespace Test;abstract class Component{   abstract public function operation(); }
登入後複製

Decorator

<?phpnamespace Test;abstract class Decorator extends Component{    protected $component;    public function __construct(Component $component)    {        $this->component = $component;    }    public function operation()    {        $this->component->operation();    }    abstract public function before();    abstract public function after();}
登入後複製

ConcreteComponent

<?phpnamespace Test;class ConcreteComponent extends Component{    public function operation()    {        echo "hello world!!!!";    }}
登入後複製

ConcreteDecoratorA 添加了before和after方法,即在原有操作的基础上之前和之后又添加了职责

<?phpnamespace Test;class ConcreteDecoratorA extends Decorator{    public function __construct(Component $component)    {        parent::__construct($component);    }    public function operation() {        $this->before();        parent::operation();        $this->after();    }    public function before()    {        // TODO: Implement before() method.        echo "before!!!";    }    public function after()    {        // TODO: Implement after() method.        echo "after!!!";    }}
登入後複製

CLient主要用来实例化装饰器

<?phpnamespace Test;class Client{    /**     *     */    public static function main() {        $decoratorA = new ConcreteDecoratorA(new ConcreteComponent());        $decoratorA->operation();        $decoratorB=new ConcreteDecoratorA($decoratorA);        $decoratorB->operation();    }}
登入後複製

调用Clien main()方法结果

before!!!hello world!!!!after!!!before!!!before!!!hello world!!!!after!!!after!!!
登入後複製
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!