dqwh1209 2010-11-26 14:04
浏览 38
已采纳

这种工厂方法对于我想做的事情来说是好的吗?


Here what I'am trying to achieve :
- this a text file parser
- depending on the first chars I create the correct parser object
- I wish to do so using the right factory pattern
- could you tell me if my code below fits correctly the factory pattern ?
- Thank you ! :-)

class Parser
{
    protected $src;

    public function __construct($src)
    {
        $this->src = $src;
    }   
}

class Format1Parser extends Parser
{
    public function Parse()
    {
        // Parsing format 1
        // ...
    }
}

class Format2Parser extends Parser
{
    public function Parse()
    {
        // Parsing format 2
        // ...
    }
}

class ParserFactory
{
    public static function GetParser($src)
    {
        $header = substr($src,0,7);
        if ( $header == "format1" )
        {
            return( new Format1Parser($src) );
        }
        if ( $header == "format2" )
        {
            return( new Format2Parser($src) );
        }
        return(false);
    }   
}

$parser = ParserFactory::GetParser( file_get_contents("file.txt") );
$parser->Parse();

  • 写回答

1条回答 默认 最新

  • dougong8012 2010-11-26 14:11
    关注

    First, I would use a suffix (Parser_Format1) instead of a prefix (Format1Parser), because IMHO it's clearer.

    As for the factory method itself, you could use dynamic instantiation:

    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;
       } 
    }
    

    Another thing, your Parser class should be abstract and define an abstract function Parse():

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

    Defining abstract methods within a base abstract class ensure that most errors (i.e.: a missing Parse method) are caught when the class is parsed (at the beginning of the program), as opposed as to when it's called (in the middle of runtime).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line