小编aci*_*dtv的帖子

正确使用装饰器

我有一个产品类.现在我想在我的网站上添加一些折扣模块,它应该与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();
Run Code Online (Sandbox Code Playgroud)

这是折扣,价格应该在网站的每个页面上调整.所以每个使用Product类的页面都应该添加装饰器.我能想到解决这个问题的唯一方法是使用一个自动添加这个装饰器的工厂.

$product = $factory->get('product'); // returns new ProductDiscountDecorator(new Product());
Run Code Online (Sandbox Code Playgroud)

它可能会工作,但我觉得我在这里滥用装饰模式.

你们对此有什么想法吗?你会如何实现这样的东西?

php design-patterns decorator

5
推荐指数
1
解决办法
252
查看次数

传递方法到功能

在Javascript中我试图将类成员传递给jQuery函数,但不知何故,该函数中的'this'对象搞砸了.这是代码:

function Hints() 
    {
    this.markProduct = function() { alert('hi'); };
    this.selectProduct = function() { this.markProduct(); }; 
    }
Run Code Online (Sandbox Code Playgroud)

当我使用这个调用此代码时:

oHints = new Hints();
oHints.selectProduct();
Run Code Online (Sandbox Code Playgroud)

它工作正常,'selectProduct'函数中的'this'对象引用Hints对象.但是,当我尝试这个:

oHints = new Hints();
$('#prodquery').keydown(oHints.selectProduct);
Run Code Online (Sandbox Code Playgroud)

'selectProduct'函数中的'this'对象引用了触发keydown事件的html对象.

有人有线索吗?我很困惑:/

javascript methods jquery

4
推荐指数
1
解决办法
859
查看次数

标签 统计

decorator ×1

design-patterns ×1

javascript ×1

jquery ×1

methods ×1

php ×1