Real world examples of Factory Method pattern

后端 未结 6 2018
醉话见心
醉话见心 2020-12-13 02:03

I just read Factory Method. I understand that it provides a way to delegate the instantiation to sub-classes. But I couldn\'t understand the possible uses in a real-world sc

6条回答
  •  不思量自难忘°
    2020-12-13 02:56

    An example php code with static creation:

    interface DbTable
    {
        public function doSomthing(): void;
    }
    
    class MySqlTable implements DbTable
    {
        public function doSomthing(): void
        {
        }
    }
    
    class OracleTable implements DbTable
    {
        public function doSomthing(): void
        {
        }
    }
    
    class TableFactory
    {    
        public static function createTable(string $type = null): DbTable
        {
            if ($type === 'oracle') {
                return new OracleTable();
            }
            return new MySqlTable(); // default is mysql
        }
    }
    
    // client
    $oracleTable = TableFactory::createTable('oracle');
    $oracleTable->doSomthing();
    

    To make it more dynamic (less modification later):

    interface DbTable
    {
        public function doSomthing(): void;
    }
    
    class MySqlTable implements DbTable
    {
        public function doSomthing(): void
        {
        }
    }
    
    class OracleTable implements DbTable
    {
        public function doSomthing(): void
        {
        }
    }
    
    class TableFactory
    {    
        public static function createTable(string $tableName = null): DbTable
        {
            $className = __NAMESPACE__ . $tableName . 'Table';
            if (class_exists($className)) {
                $table = new $className();
                if ($table instanceof DbTable) {
                   return $table;   
                }
            }
            throw new \Exception("Class $className doesn't exists or it's not implementing DbTable interface");    
        }
    }
    
    $tbl = TableFactory::createTable('Oracle');
    $tbl->doSomthing();
    

提交回复
热议问题