4

我目前正在为应用程序编写一组骨架类,从一个名为 StoreLogic 的基类开始,它包含税收规则、折扣规则等。Cart、Order、Quote 等类将扩展 StoreLogic,因为它们都将使用StoreLogic 提供的同一组方法。

一旦完成这些核心类,我将通过扩展 Cart、Order、Quote 和 StoreLogic 来实现它们,因为这些类的每个应用程序都会根据我们不同的客户需求而有所不同。覆盖父类的方法很容易,但是在他们的孩子扩展它们之前覆盖祖父类似乎......不可能?我觉得我做错了(tm)..我认为像你这样更有经验的人可能能够为我指明正确的方向。看看代码,看看你的想法!

/* My core classes are something like this: */
abstract class StoreLogic
{
    public function applyDiscount($total)
    {
        return $total - 10;
    }
}

abstract class Cart extends StoreLogic
{
    public function addItem($item_name)
    {
        echo 'added' . $item_name;
    }
}

abstract class Order extends StoreLogic
{
    // ....
}

/* Later on when I want to use those core classes I need to be able to override
 * methods from the grandparent class so the grandchild can use the new overriden
 * methods:
 */
class MyStoreLogic extends StoreLogic
{
    public function applyDiscount($total) {
        return $total - 5;
    }
}

class MyOrder extends Order
{
    // ...
}

class MyCart extends Cart
{
    public $total = 20;

    public function doDiscounts()
    {
        $this->total = $this->applyDiscount($this->total);
        echo $this->total;
    }
}

$cart = new MyCart();
$cart->doDiscounts(); // Uses StoreLogic, not MyStoreLogic..
4

1 回答 1

3

我认为您在这里缺少一个非常基本的逻辑

- MyCart extends Cart
- Cart extends StoreLogic

如果要使用MyStoreLogicthencart应定义为

 abstract class Cart extends MyStoreLogic

如果您不想这样做,那么您可以拥有

$cart = new MyCart();
$cart->doDiscounts(new MyStoreLogic()); // output 15

类修改

class MyCart extends Cart {
    public $total = 20;
    public function doDiscounts($logic = null) {
        $this->total = $logic ? $logic->applyDiscount($this->total) : $this->applyDiscount($this->total);
        echo $this->total;
    }
}
于 2012-12-19T21:20:24.483 回答