【发布时间】:2011-12-15 17:33:52
【问题描述】:
我有一个 Products 课程。现在我想向我的网站添加某种折扣模块,该模块应该与 Products 类交互。
目前我能想到的唯一解决方案是使用某种装饰器模式来包裹产品类,这样它就可以改变产品的价格。
像这样:
class Product {
function price() {
return 10;
}
}
class ProductDiscountDecorator {
private $product;
function __construct($product) {
$this->product = $product;
}
function price() {
return $this->product->price()*0.8;
}
}
$product = new ProductDiscountDecorator(new Product());
echo $product->price();
这是折扣,应在网站的每个页面上调整价格。所以每个使用 Product 类的页面也应该添加装饰器。我能想到解决这个问题的唯一方法是使用自动添加这个装饰器的工厂。
$product = $factory->get('product'); // returns new ProductDiscountDecorator(new Product());
它可能会起作用,但我觉得我在这里误用了装饰器模式。
你们对此有什么想法吗?你会如何实现这样的东西?
【问题讨论】:
标签: php design-patterns decorator