3

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

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->这很难看

你怎么看?

  • 如何以另一种方式访问​​装饰器(“儿童”)方法
  • 我如何共享属性,例如它们是否在继承的上下文中受到保护
  • 装饰器的使用不当吗?
  • 有没有更优雅的模式可以解决问题
  • parent 和这个属性是一种重新发明轮子,不是吗?

一个真实的例子:咖啡机

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();
//...
4

3 回答 3

2

仍然有点不完整,但它基本上可以做所有事情:

  1. 一切都扩展的抽象组件类。
  2. 修改扩展组件的类的抽象装饰器类。

这是很多代码,所以这里是 pastebin 链接:

[旧] http://pastebin.com/mz4WKEzD

[新] http://pastebin.com/i7xpYuLe

成分

  1. 可以互相延长
  2. 可以修改/添加/删除属性
  3. 可以与装饰器共享属性

装饰器

  1. 可以将功能附加到组件
  2. 可以修改/添加/删除组件属性

示例输入

$Sugar = 1;
$DoubleSugar = 1;

$Cofee = new SimpleCofee();
$Tea   = new SimpleTea();

$Cofee->Produce();
$Tea->Produce();

print "\n============\n\n";

if($Sugar)
{
    new SugarCube($Cofee);
    $Cofee->Produce();
    new SugarCube($Cofee);
    $Cofee->Produce();
}

if($DoubleSugar)
{
    new SugarCube($Tea);
    $Tea->Produce();
    new SugarCube($Tea);
    $Tea->Produce();
}

输出

Making coffee....
Adding Water: 150
Making cofee: array (
  'cofeee' => 25,
)
Making tea....
Adding Water: 150
Making tea: array (
  'tea' => 25,
)

============

Making coffee....
Adding sugar: 1
Adding Water: 140
Making cofee: array (
  'cofeee' => 25,
  'Spoon' => 1,
)
Making coffee....
Adding sugar: 1
Adding sugar: 1
Adding Water: 120
Making cofee: array (
  'cofeee' => 25,
  'Spoon' => 1,
)
Making tea....
Adding sugar: 2
Adding Water: 130
Making tea: array (
  'tea' => 25,
  'Spoon' => 1,
)
Making tea....
Adding sugar: 2
Adding sugar: 2
Adding Water: 90
Making tea: array (
  'tea' => 25,
  'Spoon' => 1,
)

更新

这很疯狂,但现在孩子们可以重载父函数。最重要的是,您现在可以使用数组接口$this['var']来访问共享属性。哈希将自动且透明地添加。

唯一的缺点是父母必须允许函数重载。

新输出

Making Cofee....
Adding Water: 150
Making Cofee: array (
  'cofeee' => 25,
)
Making Tea....
Adding Water: 150
Making Tea: array (
  'tea' => 25,
)

============

Making Cofee....
Adding sugar: 1
Adding Water: 140
Making Cofee: array (
  'cofeee' => 25,
  'Spoon' => 1,
)
Making Cofee....
Adding sugar: 1
Adding sugar: 1
Adding Water: 120
Making Cofee: array (
  'cofeee' => 25,
  'Spoon' => 1,
)

I have take over Produce!
But I'm a nice guy so I'll call my parent

Making Tea....
Adding sugar: 2
Adding Water: 130
Making Tea: array (
  'tea' => 25,
  'Spoon' => 1,
)

I have take over Produce!
But I'm a nice guy so I'll call my parent

Making Tea....
Adding sugar: 2
Adding sugar: 2
Adding Water: 90
Making Tea: array (
  'tea' => 25,
  'Spoon' => 1,
)

============

DoubleSugarCube::SuperChain(array (
  0 => 'test',
))
SugarCube::SuperChain(array (
  0 => 'DoubleSugarCube',
))
SimpleTea::SuperChain(array (
  0 => 'SugarCube',
))
SimpleCofee::SuperChain(array (
  0 => 'SimpleTea',
))

更新

这是我的最终草稿。我不能一点一点地改变我的解决方案。如果有错误,请在列表中说明所有内容。

删除 callparent 并将其所有功能放入parent::function

  1. 孩子可以使用父母的财产。
  2. 子级可以重载父级函数。
  3. 重载将从基类开始一直到abstract class Decorator类。然后从传递给构造函数的父级获得属性/方法。
  4. 你说你喜欢你分享财产的方法。所以我懒得回答这个问题。

我希望你现在能接受答案。如果没有,那么我期待你的。我希望当您整理好所有内容时,您会与我们其他人分享。

干杯

于 2013-11-18T18:47:55.530 回答
2

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

一种解决方案是为受保护的变量定义 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);

我希望这回答了你的问题!

评论后编辑

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

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();
//...
于 2013-11-12T18:51:58.350 回答
1

有解决咖啡机问题的解决方案

abstract class Coffee { 
    protected $cup = array();
    public function getCup() {
        return $this->cup;
    } 
}   
class SimpleCoffee extends Coffee {
    public function __construct() {
        $this->cup['coffeePowder'] = 1;
        $this->cup['water']        = 20;
        $this->cup['spoon']        = FALSE;
    }
}

abstract class Decorator extends Coffee { 
    private $_handler = null;

    public function __construct($handler) {
        $this->_handler = $handler;
        $this->cup      = $handler->cup;
    }
}

class SugarCoffee extends Decorator {
    public function __construct($handler) {
        parent::__construct($handler);
        $this->cup['water'] -= 1;
        $this->cup['sugar']  = 1;
        $this->cup['spoon']  = TRUE;
    }
}
class MilkCoffee extends Decorator{
    public function __construct($handler) {
        parent::__construct($handler);
        $this->cup['water'] -= 5;
        $this->cup['milk']    = 5;
    }
}

$wantSugar = TRUE;
$wantMilk  = TRUE;

$coffee = new SimpleCoffee();
if($wantSugar)
    $coffee = new SugarCoffee($coffee);
if($wantMilk)
    $coffee = new MilkCoffee($coffee);

$cupOfCoffee = $coffee->getCup();

var_dump($cupOfCoffee);

还有一个real world example,希望对你有帮助:

abstract class MessageBoardHandler {
    public function __construct(){}
    abstract public function filter($msg);
}
class MessageBoard extends MessageBoardHandler {
    public function filter($msg) {
        return "added in messageBoard|".$msg;
    }
}
class MessageBoardDecorator extends MessageBoardHandler {
    private $_handler = null;
    public function __construct($handler) {
        parent::__construct(); 
        $this->_handler = $handler;
    }
    public function filter($msg) {
        return $this->_handler->filter($msg);
    } 
}
class HtmlFilter extends MessageBoardDecorator {
    public function __construct($handler) {
        parent::__construct($handler);
    } 
    public function filter($msg) {
        return "added in html filter|".parent::filter($msg);
    }   
}   
class SensitiveFilter extends MessageBoardDecorator {
    public function __construct($handler) {
        parent::__construct($handler);
    }   
    public function filter($msg) {
        return "added in sensitive filter|".parent::filter($msg);
    }   
}
$html      = TRUE;
$sencitive = TRUE;
$obj = new MessageBoard();
if($html) {
    $obj = new SensitiveFilter($obj);
}
if($sencitive) {
    $obj = new HtmlFilter($obj);
}
echo $obj->filter("message");
于 2013-11-12T14:02:08.667 回答