2012-04-30 47 views
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对象并研究其他逻辑?或者有没有办法“重建”物品对象并将其转换为瓶子?

回答

2

这是什么时候使用Factory Pattern的完美例子。

对于你的代码,你可以做这样的事情。

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)

工厂模式,当你有很多有相同的基础(或父)类的对象是有用的,你需要确定他们是在什么课运行。

+0

工厂+1,但链接已关闭,因此:http://www.dofactory.com/Patterns/PatternAbstract.aspx –

相关问题