php之裝飾者模式

裝飾者模式概念

動態地將責任附加到對象上,若要擴展功能,裝飾者提供了比繼承更有彈性的替代方案php

裝飾者模式結構圖

clipboard.png

裝飾者角色

1.被裝飾者基類(Compoent):對象組件
2.待裝飾對象(ConcreteComponent):具體組件角色,即將要被裝飾增長功能的類
3.裝飾者基類(Decorator):須要定義一個與組件接口一致的接口,並持有一個Component對象,該對象其實就是被裝飾的對象。
4.具體裝飾者(ConcreteDecorator):現具體要向被裝飾對象添加的功能。用來裝飾具體的組件對象或者另一個具體的裝飾器對象設計模式

實例代碼

<?php


//被裝飾者基類
interface Component{
    public function  operation();
}

//裝飾者基類
abstract class Decorator implements Component{
    protected $component;

    public function __construct(Component $component)
    {
        $this->component = $component;
    }

    public function operation()
    {
        $this->component->operation();
    }
}


//具體裝飾者類
class ConcreteComponent implements Component{
    public function operation(){
        return 'do operation';
    }
}

//具體裝飾者a
class ConcreteDecoratorA extends Decorator{

    public function __construct(Component $component)
    {
        parent::__construct($component);
    }

    public function operation()
    {
        parent::operation();
        $this->addOperationA();
    }

    public function addOperationA(){
        return 'add operation a';
    }
}

//具體裝飾者類b
class ConcreteDecoratorB extends Decorator{

    public function __construct(Component $component)
    {
        parent::__construct($component);
    }

    public function operation()
    {
        parent::operation(); 
        $this->addOperationB();
    }

    public function addOperationB(){
        echo 'add operation b';
    }
}

$decoratorA = new ConcreteDecoratorA(new ConcreteComponent());
$decoratorA->operation();

總結

1.裝飾者和被裝飾者對象有相同的超類型
2.你能夠用一個或者多個裝飾者包裝一個對象
3.既然裝飾者和被裝飾者對象有相同的超類,因此在任何須要原始對象(被包裝的)的場合,能夠用裝飾過的對象替換他
4.(關鍵點)裝飾者能夠在委託被裝飾者的行爲以前/以後,加上本身的行爲,已達到特意的目的
5.對象能夠在任什麼時候候被裝飾,因此能夠在運行時動態的、不限量的用你喜歡的裝飾者來裝飾對象this

參考文獻《head first 設計模式》spa

相關文章
相關標籤/搜索