0
让我们说我有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对象并研究其他逻辑?或者有没有办法“重建”物品对象并将其转换为瓶子?
工厂+1,但链接已关闭,因此:http://www.dofactory.com/Patterns/PatternAbstract.aspx –