欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

php装饰模式

程序员文章站 2022-06-10 18:14:37
...
跳至
/**
 * 抽象构件角色
 */
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();
    }
}
 
/**
 * 具体装饰类A
 */
class ConcreteDecoratorA extends Decorator {
    public function __construct(Component $component) {
        parent::__construct($component);
 
    }
 
    public function operation() {
		
        parent::operation();    //  调用装饰类的操作
        $this->addedOperationA();   //  新增加的操作
    }
 
    /**
     * 新增加的操作A,即装饰上的功能
     */
    public function addedOperationA() {
        echo 'Add Operation A 
';
    }
}
 
/**
 * 具体装饰类B
 */
class ConcreteDecoratorB extends Decorator {
    public function __construct(Component $component) {
        parent::__construct($component);
 
    }
 
    public function operation() {
        parent::operation();//父类根据对象进行委派
        $this->addedOperationB();
    }
 
    /**
     * 新增加的操作B,即装饰上的功能
     */
    public function addedOperationB() {
        echo 'Add Operation B 
';
    }
}
 
/**
 * 具体构件
 */
class ConcreteComponent implements Component{
 
    public function operation() {
        echo 'Concrete Component operation 
';
    }
 
}
 
/**
 * 客户端
 */
class Client {
 
     /**
     * Main program.
     */
    public static function main() {
        $component = new ConcreteComponent();
        $decoratorA = new ConcreteDecoratorA($component);
        $decoratorB = new ConcreteDecoratorB($decoratorA);
 
        $decoratorA->operation();
        $decoratorB->operation();
    }
 
}
 
Client::main();
链接地址:http://www.phppan.com/2010/06/php-design-pattern-4-decorator/

相关标签: php装饰模式