简体   繁体   中英

Factory Design Pattern in PHP, Is this correct?

I'm reading about Design Patterns in PHP, and, I'm skeptical of the code which I'd written to implement the Factory Design Pattern.

Does this code implement REAL Factory Design?

And, Do I need to use any interface here?

The code is:

class DBFactory 
{
   const MYSQL      =   1;
   const ORACLE     =   2;
   const SQLITE     =   3;

   private $objectTxt = null;

   function __construct($type) 
   {
       if ($type == self::MYSQL) {
           $this->objectTxt = 'MySQL Object'; 
           return ; //MySQL Object
       }

       else if ($type == self::ORACLE) 
       {
           $this->objectTxt = 'Oracle Object';
           return ; //Oracle Object
       }

       else if ($type == self::SQLITE)
       {
           $this->objectTxt = 'SQlite Object';
           return 'SQLite Object'; //SQLite Object           
       }
   }

   function __toString() {
        return $this->objectTxt;   
   }
}

Yes, that's implements the Factory Design Pattern , but, it's much better to use a static method, as follows:

public static function getInstance($type) { ... }

To get an instance:

$db = DBFactory::getInstance(DBFactory::MYSQL);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM