何时应实例化儿童类



假设我有 3 件物品:键盘、一件 T 恤和一瓶可乐。

$keyboard = new Item("Keyboard");
echo $keyboard->getPrice(); // return 50;
$tshirt = new Item("Tshirt");
echo $tshirt->getPrice(); // return 20;
$cola = new Item("Cola");
echo $cola->getPrice(); // return 0 or 2 whether the bottle is empty or not.

获得一瓶可乐Price的最佳实践是什么?

我从创建 2 个类开始:

Class Item {
    $this->price;
    function __construct($name) {
    // ...
    }
    public function getPrice() {
        return $this->price;
    }
}
Class Bottle extends Item {
    $this->empty;
    function __construct($name) {
    // get from database the value of $this->empty
    }
    public function getPrice() {
        if($this->empty)
            return 0;
        else 
            return $this->price;
    }
}

但是现在我想知道;当我使用:$cola = new Item("Cola");时,我正在实例化一个Item对象而不是一个Bottle对象,因为我还不知道它是一个"普通"项目还是一个瓶子。

我应该实例化一个 Bottle 对象并在我的应用程序中研究另一个逻辑吗?或者有没有办法"重新创建"项目对象并将其转换为瓶子?

这是何时使用工厂模式的完美示例。

对于您的代码,您可以执行类似操作。

class ItemFactory {
    // we don't need a constructor since we'll probably never have a need
    // to instantiate it.
    static function getItem($item){
        if ($item == "Coke") {
            return new Bottle($item);
        } else if ( /* some more of your items here */){
            /*code to return object extending item*/
        } else { 
            // We don't have a definition for it, so just return a generic item.
            return new Item($item);
        }
    }
}

你可以像$item = ItemFactory::getItem($yourvar)一样使用它

当您有许多具有相同基(或父)类的对象,并且您需要确定它们在运行时是什么类时,工厂模式非常有用。

最新更新