duanhan7001 2013-01-30 14:52
浏览 57
已采纳

了解工厂设计模式

I was learning about factory design pattern in php. From what i understand, this pattern is useful in cases where we have a bunch of classes, lets say, class_1, class_2, class_3 etc. If the particular class which has to be instantiated is known only at runtime, then instead of using the new operator to create the objects for these classes we create a factory class which will do the job for us.

The factory class will look somewhat like this:

class Factory
{
// $type will have values 1, 2, 3 etc.
public function create_obj($type)
{
  $class_name = "class_".$type;
  if(class_exists($class_name))
  {
        return new $class_name();
  } 
}
}

My question is what is the advantage in using a factory class here? why not just use a simple function instead of a class which is going to complicate things?

  • 写回答

4条回答 默认 最新

  • dongsheng9203 2013-01-30 16:44
    关注

    The method in your code snippet is not a factory method, but merely a helper method which does a well-known reflective task: instantiates a class based on its name. This is exactly the opposite of what a Factory pattern is for: creating objects (products) without specifying the exact class of object that will be created.

    As explained in Wikipedia:

    The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate."

    You are probably confused by the last PHP example in the Wikipedia article on Factory pattern, and yes, it is a bad example. Check the Java example just above that for a meaningful example (whoever tried to convert that to PHP missed the whole point). The Java example returns a file reader based on its extension, and that is exactly the use case for a factory pattern. Creating your own personal "rule" that certain classes need to have a certain name prefix is most likely a bad design decision.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集