i want parse several files formats. wondering if it's correct oop "take risk" create object nothing.
class parserfactory { private fn; public function parserfactory(fn) { this->fn = fn; } public function getparser() { = new formataparser(this->fn); if ( a->isvalid() ) { return( ); } b = new formatbparser(this->fn); // ... , on... } } class formataparser { /* object telling if able continue work... **clean or dirty design ?** */ public function isvalid() { header = someconversionandreadingstuff(); if ( header != "formata" ) { return(false) } return(true); } public function parse() { /* parsing, using conversion stuff done in isvalid */ } }
thanks
edit
had answers. so, ok object check own validity. anyway, code un-oop because of procedural way select parser (format detection). improve this, better user factory pattern 1 (php code) :
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 $parserclass ) { $parser = new $parserclass(); $parser->setraw($raw); if ( $parser->isvalid() ) { return( $parser ); } } } } parserfactory::registerparser("parsera"); parserfactory::registerparser("parserb"); parserfactory::getparser("b");
a more common design
public function getparser() { if (formataparser::isrecognizedheader(this->fn) { return new formataparser(this->fn); } if (formatbparser::isrecognizedheader(this->fn) { return new formatbparser(this->fn); } }
this uses class, not object method check header. obvious variation collect different parsers in list, instead of manually looping on them this. requires ability add classes (not objects) list.
Comments
Post a Comment