需要设计模式的建议



我需要为我的简单项目提供建议。这是一个记录器系统。我有以下文件/类

文件

- 检查文件是否存在可读等

ConfigParser - 它是一个抽象类,我使用它__construct方法来做一些事情。该类永远不会直接实例化。这是一个装饰器。

abstract class ConfigParser
{
    protected $filename;
    public function __construct($file)
    {
       // Here I want to invoke validate() method of File class
       // I know that I can do $file = new File(); $file->validate()
       // but the idea is to keep the things decoupled
       // Also I know that I can extend the File class ConfigParser extends File
       // but this doesn't make sence
       // I can pass the File object on child class new XmlParser('file.xml', $fileObj)
       // but this doesn't make sence too.
       // I don't want to use traits as it's bizarre for me
    }
}

XmlParser - 扩展 ConfigParser

IniParser - 扩展 ConfigParser

由于项目目标是保持类分离,因此我无法弄清楚在这种情况下如何实现 File 类。

我认为在构造函数中进行验证不是一个不错的设计。构造函数应该简单地创建解析器,并可能做一些简单的事情。

您可以做的是使用模板方法模式,然后在父类中进行验证,并将实际解析委托给实际的解析器类。

abstract class ConfigParser {
  final function parse(){
     $file->validate();
     $this->conreteParse();
  }
  abstract function concreteParse();
}

最新更新