我想解析幾種文件格式。我想知道是否正確的面向對象「冒險」創建一個空虛的對象。對象自己拒絕它是否正確?
class ParserFactory
{
private fn;
public function ParserFactory(fn)
{
this->fn = fn;
}
public function getParser()
{
a = new FormatAParser(this->fn);
if (a->isValid())
{
return(a);
}
b = new FormatBParser(this->fn);
// ... and so on...
}
}
class FormatAParser
{
/*
The object is telling us if is able to continue to work...
**CLEAN OR DIRTY DESIGN ?**
*/
public function isValid()
{
header = SomeConversionAndReadingStuff();
if (header != "formatA")
{
return(false)
}
return(true);
}
public function parse()
{
/*
Do the parsing, using the conversion stuff done in isValid
*/
}
}
感謝
編輯
我有很好的答案。所以,對象檢查自己的有效性是可以的。無論如何,我的代碼是un-OOP,因爲我選擇一個解析器(格式檢測)的過程方式。爲了改善這一點,最好是用戶一個工廠模式像這樣的(PHP代碼):
class Parser
{
protected $raw;
public function setRaw($raw)
{
$this->raw = $raw;
}
}
class ParserA extends Parser
{
public function __construct()
{
echo "ParserA constructor\n";
}
public function isValid()
{
if ($this->raw == "A")
{
return(true);
}
return(false);
}
}
class ParserB extends Parser
{
public function __construct()
{
echo "ParserB constructor\n";
}
public function isValid()
{
if ($this->raw == "B")
{
return(true);
}
return(false);
}
}
class ParserFactory
{
static private $parserClasses = array();
public static function registerParser($parserClassName)
{
self::$parserClasses[] = $parserClassName;
}
public static function getParser($raw)
{
foreach(self::$parserClasses as $parserClass)
{
$parser = new $parserClass();
$parser->setRaw($raw);
if ($parser->isValid())
{
return($parser);
}
}
}
}
ParserFactory::registerParser("ParserA");
ParserFactory::registerParser("ParserB");
ParserFactory::getParser("B");
查看我對Jaydel的回答:我認爲這樣會更好呃做一次轉換的東西比做兩次。 – Antoine 2010-12-21 15:18:06
Tim Barrass的組合解釋:非常感謝!我會更新我的問題,添加一些關於工廠模式的內容 – Antoine 2010-12-21 16:06:55