装饰器模式


当我们在一个类的功能上需要添加额外的功能时候,在传统的编程方式里要么过程式的在核心代码外包围一连串的额外功能代码或者写一个子类集成它重写这个类的方法。

使用装饰模式,我们可以动态地添加修改类的功能,仅需在运行时添加一个装饰器对象即可,实现了极大的灵活性。

被装饰类:

class  {
    function write(){
        echo "write some thing" ;
    }
}

传统方式1——过程式:

class  {

    function wirte(){

        
        echo "before write some thing" ;

        echo "wirte some thing" ;

        /*结束*/
        echo "after write some thing" ;
    }

}

传统方式2——继承父类:

class SubDataClass extends {
    function write(){
        
        echo "before write some thing" ;

        parent::write() ;    

        /*结束*/
        echo "after write some thing" ;
    }
}

装饰模式:

/*定义装饰器接口*/
interface Decorator{
    function before() ;
    function after() ;
}

/*定义装饰器*/
class SizeDecorator implments Decorator {
    function before(){
        echo '<div style="font-size:20px;">' ;
    }

    function after(){
        echo '<div>'
    }
}

/*主体*/
class DataClass {
    private $decorator = array() ;

    public function addDecorator(Decorator $de){
        $this->decorator[] = $de ;    
    }

    private function before(){
        foreach($this->decorator as $de){
            $de->before() ;
        }
    }

    private function after(){
        /*反转*/
        $des = array_reverse($this->decorator)
        foreach(des as $de){
            $de->after() ;
        }
    }

    function write(){
        $this->before() ;

        echo "wirte some thing" ;

        $this->after() ;
    }
}

/*控制器*/
$c = new DataClass() ;
$c->addDecorator(new SizeDecorator()) ;
$c->write() ;

更多设计模式