English 中文(简体)
矫正器的使用
原标题:Correct use of a decorator

我有一个产品类别。 现在,我想在我的网站上添加某种贴现模块,与产品类别互动。

目前唯一的解决办法 我可以认为,正在使用某种装饰模式,围绕产品类别进行包装,从而改变产品价格。

与此类似:

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 = $factory->get( product ); // returns new ProductDiscountDecorator(new Product());

也许会奏效,但我感到,我对这里的诽谤模式怀念。

你们对此是否有任何想法? 你们如何执行类似的东西?

最佳回答

裁决者是一种选择。 另一种选择是利用战略模式计算贴现

Example

class Product
{
    protected $discountStrategy;
    protected $price;

    public function __construct(DiscountStrategy $discountStrategy)
    {
        $this->discountStrategy = $discountStrategy;
    }

    public function getPrice()
    {
        return $this->discountStrategy->applyDiscount($this->price);
    }
}

之后,将各种可能的折扣限制在自己的类别中:

interface DiscountStrategy 
{
    public function applyDiscount($cent);
}

class NoDiscount implements DiscountStrategy
{
    public function applyDiscount($cent)
    {
        return $cent;
    }
}

class PremiumDiscount implements DiscountStrategy
{
    public function applyDiscount($cent)
    {
        return $cent - $cent * 0.8;
    }
}

您仍然使用工厂组装产品,但战略更为细微,你也可以在其他情况下重新使用这些产品,例如,一些忠诚的客户也可获得折扣,即使产品本身也带有贴现。

问题回答

总体上看好。

为了遵守良好业务管理设计原则,我还将确定“产品”接口。

页: 1

interface IProduct { public function getPrice(); }

商品和服务贸易及初级商品委员会

class Product implements IProduct { ... }
class ProductDiscountDecorator implements IProduct { ... }




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签