php - 在 php 中使用 Decorator 的完整继承行为

标签 php oop inheritance decorator decorator-chaining

我一般不太习惯设计pattern,也没用过Decorator。我想要一个可以根据上下文具有不同行为的对象。这些行为在不同的类中定义。我想装饰器可以解决问题。但我需要每个装饰器都可以访问相同的属性,并首先调用子方法,就像继承一样。所以这是我所做的:

abstract class Component{

    /**
     * Used to access last chain Decorator
     *
     * @var Decorator
     */
    protected $this;

    protected $prop1;//These properies have to be accessed in any decorators

    protected $prop2;

    protected $prop3;

    //this method is used to share properties with the childrens
    public function getAttributesReferencesArray() {
        $attributes=[];
        foreach($this as $attr=>&$val)
                $attributes[$attr]=&$val;
        return $attributes;
    }

}

class Foo extends Component{

    public function __construct() {
        $this->prop1="initialized";
        //...
    }

    public function method1() {//this method can be "overrided" and called here
        //...
    }

    public function method2() {//this method call the overrided or not method1
        //...
        $this->this->method1();
        //...
    }

}

abstract class Decorator extends Component{

    /**
     * Used to access parent component
     *
     * @var Component
     */
    protected $parent;

    public function __construct(Component $parent) {
        $attributes=$parent->getAttributesReferencesArray();
        foreach($attributes as $attr=>&$val)
                $this->{$attr}=&$val;
        $this->parent=$parent;
        $this->this=$this;
    }

    public function __call($method, $args) {
        if(!$this->parent instanceof Decorator &&
            !method_exists($this->parent, $method))
                throw new Exception("Undefined method $method attempt.");
        return call_user_func_array(array($this->parent, $method), $args);
    }

}

class Bar extends Decorator{

    //this method call the component method (I guess Decorator classical way)
    public function method1(){
        //...
        $this->parent->method1();
        $this->prop2="set in Bar";
    }
}

class Baz extends Decorator{

    public function method2(){//this method call the overrided or not method1
        //...
        $this->this->method1();
        //...
    }

}

现在我们可以根据上下文“构造”“继承”了:

//...
$obj=new Foo();
if($context->useBar())
        $obj=new Bar($obj);
if($context->somethingElse())
        $obj=new Baz($obj);

并运行带有行为抽象的对象:

$obj->method1();
//...

它做了我想要的,但是:

  • 不再有封装
  • $this-> parent 很丑
  • $this->这很丑

你怎么看?

  • 如何以其他方式访问装饰器(“子级”)方法
  • 我如何共享属性,比如它们在继承上下文中受到保护
  • 是否是 Decorator 的错误用法?
  • 是否有一些更优雅的模式可以解决问题
  • parent 和 this 属性是一种重新发明轮子,不是吗?

现实世界的例子:咖啡机

abstract class CoffeeFactory{// Component

    /**
     * Used to access last chain Decorator
     *
     * @var Decorator
     */
    protected $this;

    /**
     * Used to access user choices
     *
     * @var CoffeeMachine
     */
    protected $coffeeMachine;

    protected $water;//the water quantity in cl

    protected $coffeePowder;

    protected $isSpoon=FALSE;

    protected $cup=[];

    //this method is used to share properties with the childrens
    public function getAttributesReferencesArray() {
        $attributes=[];
        foreach($this as $attr=>&$val)
                $attributes[$attr]=&$val;
        return $attributes;
    }

}

class SimpleCoffeeFactory extends CoffeeFactory{//Foo

    public function __construct(CoffeeMachine $coffeeMachine) {
        $this->coffeeMachine=$coffeeMachine;
        $this->water=$coffeeMachine->isEspresso()?10:20;
        $this->coffeePowder=$coffeeMachine->isDouble()?2:1;
        $this->water-=$this->coffeePowder;
        $this->this=$this;
    }

    private function addCoffeePowder(){
        $this->cup["coffeePowder"]=$this->coffeePowder;
    }

    private function addSpoon(){
        if($this->isSpoon)
                $this->cup["spoon"]=1;
    }

    public function isWaterHot($boilingWater){
        return $this->getWaterTemperature($boilingWater)>90;
    }

    private function addWater() {
        $boilingWater=$this->getWaterForBoiling($this->water);
        while(!$this->this->isWaterHot($boilingWater))
                $this->boilWater($boilingWater);
        $this->cup["water"]=$boilingWater;
    }

    public function prepare() {
        $this->addCoffeePowder();
        $this->addSpoon();
    }

    public function getCup() {
        $this->this->prepare();
        $this->addWater();
        return $this->cup;
    }

}

abstract class Decorator extends CoffeeFactory{

    /**
     * Used to access parent component
     *
     * @var Component
     */
    protected $parent;

    public function __construct(Component $parent) {
        $attributes=$parent->getAttributesReferencesArray();
        foreach($attributes as $attr=>&$val)
                $this->{$attr}=&$val;
        $this->parent=$parent;
        $this->this=$this;
    }

    public function __call($method, $args) {
        if(!$this->parent instanceof Decorator &&
            !method_exists($this->parent, $method))
                throw new Exception("Undefined method $method attempt.");
        return call_user_func_array(array($this->parent, $method), $args);
    }
}

class SugarCoffeeFactory extends Decorator{

    protected $sugar;

    public function __construct(Component $parent) {
        parent::__construct($parent);
        $this->sugar=$this->coffeeMachine->howMuchSugar();
        $this->water-=$this->sugar;
        $this->isSpoon=TRUE;
    }

    public function prepare() {
        $this->cup['sugar']=$this->sugar;
        $this->parent->prepare();
    }
}

class MilkCoffeeFactory extends Decorator{

    protected $milk;

    public function __construct(Component $parent) {
        parent::__construct($parent);
        $this->milk=$this->coffeeMachine->howMuchMilk();
        $this->water-=$this->milk;
    }

    public function prepare() {
        $this->parent->prepare();
        $this->cup['milk']=$this->milk;
    }

    public function isWaterHot($boilingWater){
        //The milk is added cold, so the more milk we have, the hotter water have to be.
        return $this->getWaterTemperature($boilingWater)>90+$this->milk;
    }

}

//Now we can "construct" the "inheritance" according to the coffee machine:

//...
$coffeeFactory=new SimpleCoffeeFactory($coffeeMachine);
if($coffeeMachine->wantSugar())
        $coffeeFactory=new SugarCoffeeFactory($coffeeFactory);
if($coffeeMachine->wantMilk())
        $coffeeFactory=new MilkCoffeeFactory($coffeeFactory);

//and get our cup with abstraction of behaviour:

$cupOfCoffee=$coffeeFactory->getCup();
//...

最佳答案

Decorator 模式不是为了在基类中进行内部更改(您称其为父类)。您正在做的是对这种模式的错误使用。装饰器应该只改变函数的输出而不是玩弄变量。

一种解决方案是为 protected 变量定义 getter 和 setter,并从装饰器中调用它们。

另一种解决方案是我个人更喜欢的,它是拆分依赖于上下文和基类的行为:

class Component {
    protected $behaviour;
    function __construct() {
        $this->behaviour = new StandardBehaviour();
    }

    function method1() {
        $this->prop2 = $this->behaviour->getProp2Value();
    }
    function setBehaviour(Behaviour $behaviour) {
        $this->behaviour = $behaviour;
    }
}

abstract class Behaviour {
    abstract function getProp2Value();
}

class StandardBehaviour extends Behaviour {
    function getProp2Value() {
        return 'set by bahaviour ';
    }
}

class BarBehaviour extends StandardBehaviour {
    function getProp2Value() {
        return parent::getProp2Value().' Bar';
    }
}

class BazBehaviour extends BarBehaviour {
    function getProp2Value() {
        return 'set in Baz';
    }
}

现在我们可以这样使用它了:

$obj=new Foo();
if($context->useBar())
    $obj->setBehaviour(new BarBehaviour);
if($context->somethingElse())
    $obj->setBehaviour(new BazBehaviour);

我希望这能回答您的问题!

评论后编辑

我理解您的观点,即行为相互替换而不是链接。这确实是装饰器类的典型问题。但是,您真的不应该更 retrofit 饰器类中的原始类。装饰器类仅“装饰”原始输出。下面是装饰器模式如何在您提到的现实世界场景中使用的典型示例:

interface ICoffeeFactory {
    public function produceCoffee();
}

class SimpleCoffeeFactory implements ICoffeeFactory{
    protected $water;//the water quantity in cl

    public function __construct() {
        $this->water=20;
    }

    protected function addCoffeePowder($cup){
        $cup["coffeePowder"]=1;
        return $cup;
    }

    protected function addWater($cup) {
        $cup["water"]=$this->water;
        return $cup;
    }

    public function produceCoffee() {
        $cup = array();
        $cup = $this->addCoffeePowder($cup);
        $cup = $this->addSpoon($cup);
        $cup = $this->addWater($cup);
        return $cup;
    }

}

class EspressoCoffeeFactory extends SimpleCoffeeFactory {
    public function __construct() {
        $this->water=5;
    }

    protected function addCoffeePowder($cup){
        $cup["coffeePowder"]=3;
        return $cup;
    }
}

abstract class Decorator implements ICoffeeFactory {
    function __construct(ICoffeeFactory $machine)
}

class SugarCoffee extends Decorator{
    public function produceCoffee() {
        $cup = $this->factory->produceCoffee();
        if ($cup['water'] > 0)
            $cup['water'] -= 1;

        $cup['spoon']  = TRUE;
        $cup['sugar'] += 1;
        return $cup;
    }
}

class MilkCoffee extends Decorator{
    protected function produceCoffee() {
        $cup = $this->factory->produceCoffee();
        $cup['milk'] = 5;
        return $cup;
    }
}

//Now we can "construct" the "inheritance" according to the coffee machine:

//...
$coffee=new SimpleCoffeeFactory();
if($coffeeMachine->wantSugar())
        $coffee=new SugarCoffee($coffee);
if($coffeeMachine->wantMilk())
        $coffee=new MilkCoffee($coffee);

//and get our cup with abstraction of behaviour:

$cupOfCoffee=$coffee->produceCoffee();
//...

关于php - 在 php 中使用 Decorator 的完整继承行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18114141/

相关文章:

php - 搜索未按预期工作

php - 是否可以使用 Composer 从 Gitlab 上的存储库安装软件包?

c++ - 本地 CGEventRef 是否被视为指针?

javascript匿名函数作用域

c++ - 在 OO 编程中,继承对运行时有哪些负面影响?

c# - 从 Canvas 继承

php - BindValue 不接受假值

php - 具有一些特殊要求的多行排序

perl - 是否可以获得特定 Perl 类的所有有效方法?

css - 继承了哪些 CSS 属性?