【问题标题】:Is this Factory Method the good one for what I'am trying to do?这个工厂方法是我想做的好方法吗?
【发布时间】:2011-05-16 05:09:29
【问题描述】:


这是我想要实现的目标:
- 这是一个文本文件解析器
- 根据第一个字符,我创建了正确的解析器对象
- 我希望使用正确的工厂模式
- 你能告诉我下面的代码是否符合工厂模式吗?
- 谢谢 ! :-)

类解析器 { 受保护的 $src; 公共函数 __construct($src) { $this->src = $src; } } 类 Format1Parser 扩展 Parser { 公共函数解析() { //解析格式1 // ... } } 类 Format2Parser 扩展 Parser { 公共函数解析() { //解析格式2 // ... } } 类 ParserFactory { 公共静态函数 GetParser($src) { $header = substr($src,0,7); if ( $header == "format1" ) { 返回(新的 Format1Parser($src)); } if ( $header == "format2" ) { 返回(新的 Format2Parser($src)); } 返回(假); } } $parser = ParserFactory::GetParser(file_get_contents("file.txt")); $解析器->解析();

【问题讨论】:

    标签: php design-patterns methods factory


    【解决方案1】:

    首先,我会使用后缀 (Parser_Format1) 而不是前缀 (Format1Parser),因为恕我直言,它更清晰。

    至于工厂方法本身,你可以使用动态实例化:

    class ParserFactory {
       static public function getParser($src) {
          // may want to change the following line, because it assumes your parser
          // type is always 7 characters long.
          $type = substr($src, 0, 7); 
    
          $pattern = 'Parser_%type';
          $className = str_replace('%type', $type, $pattern);
          if (!class_exists($className)) {
             throw new InvalidArgumentException("Invalid parser $type");
    
          return new $className;
       } 
    }
    

    另外,你的 Parser 类应该是抽象的并且定义一个抽象函数Parse():

    abstract class Parser {
        protected $src;
    
        public function __construct($src)
        {
            $this->src = $src;
        }   
    
        abstract public function Parse();
    }
    

    在基本抽象类中定义抽象方法可确保在解析类时(在程序开头)而不是在调用它时(在运行时的中间)。

    【讨论】:

    • 感谢您的回答。事实上,代码比你做的更好。但我的问题不好。好的一个是“我的代码是否正确地符合工厂方法模式?”,以及“有没有更好的模式来做到这一点?”
    • 嗯,工厂模式的目的是创建相同类型的类(本例中为解析器)。所以你的实现很好。就像我说的,你应该将你的 Parser 类更改为抽象类,以防止运行时错误。
    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多