40

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 scenario.

Can anyone give one typical example showing how Factory method pattern can be used so that I can relate to what I have read.

A problem statement for which factory method pattern is the best solution would be sufficient to make it clear.

Ravi
  • 30,829
  • 42
  • 119
  • 173
softwarematter
  • 28,015
  • 64
  • 169
  • 263

5 Answers5

54

A class implementing factory design pattern works as bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as backend, but in future need to change backend database to oracle, you will need to modify all your code, if you haven’t written your code following factory design pattern.

In factory design pattern you need to do very little work to achieve this. A class implementing factory design pattern takes care for you and lessen your burden. Switching from database server won’t bother you at all. You just need to make some small changes in your configuration file.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 3
    above sample code is currently unavailable. so i found this link and its useful.. http://www.primaryobjects.com/CMS/Article81.aspx – DevT Jan 14 '13 at 17:48
  • 2
    Why not just use a common interface and dependency injection? e.g. `IDatabase` It seems the factory pattern is overkill in a situation where DI will handle it just fine. – Levi Fuller Dec 18 '19 at 04:11
  • @LeviFuller I guess you could but at least in the example in the link you wouldnt be able to add for example connection string to an interface – cah1r Oct 19 '21 at 05:11
  • @cah1r You can also use a resolver to solve the problem of having multiple dependencies with the same interface or use a separate interface for different connections – Levi Fuller Jan 03 '22 at 22:03
9

An example php code with static creation:

interface DbTable
{
    public function doSomething(): void;
}

class MySqlTable implements DbTable
{
    public function doSomething(): void
    { }
}

class OracleTable implements DbTable
{
    public function doSomething(): 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->doSomething();

To make it more dynamic (less modification later):

interface DbTable
{
    public function doSomething(): void;
}

class MySqlTable implements DbTable
{
    public function doSomething(): void
    { }
}

class OracleTable implements DbTable
{
    public function doSomething(): 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->doSomething();
M Rostami
  • 4,035
  • 1
  • 35
  • 39
  • 2
    This looks more like Simple Factory than Factory method pattern. As per my understanding, factory method pattern provides multiple concrete factories that create instances of Concrete products that inherit from the same Abstract product. If I feel only one factory is enough to decide which concrete product to instantiate based on a type string (or enum) passed by the client, even Simple factory would be good enough. Why do we need to use Factory method pattern in such a case? – ndh May 15 '19 at 16:12
  • @ndh made some changes :) – M Rostami May 15 '20 at 08:58
3

From API I'm developing right now:

WebGalleryFactory factory = WebGalleryFactory.newInstance (WebGalleryType.PICASA);
WebAlbum album = factory.createAlbum (title, description);

In this example I use Factory Method to create Abstract Factory of a certain type (PICASA in the example).

These two patterns are often used together.

Roman
  • 64,384
  • 92
  • 238
  • 332
3

Zend_Db uses it in it's Zend_Db_Adapter class to allow the creation of different kinds of database objects based on database settings passed through from a configuration object.

Tobias Cohen
  • 19,893
  • 7
  • 54
  • 51
  • Other examples of factory methods: Zend_Cache::factory(), Zend_Memory::factory(). Zend_Log_Writer also has factory methods for initializing concrete adapters of Zend_Log_Writer_Abstract. One thing has to be noted though: those implementations are generally in form when factory method is injected directly into product (that's there is no separate AbstractCreator/ConcreteCreator classes). – Victor Farazdagi Nov 07 '10 at 14:09
  • Just re-checked the code: ZF actually utilizes what is called Simple Factory, which is idiom and not a pattern (described say in HF Design Patterns). I also saw bunch of static factory methods, at least implementation was very similar to what Bloch's discussed in Effective Java. And I couldn't locate exact GoF's implementation of Factory Method Pattern. – Victor Farazdagi Nov 08 '10 at 01:41
2

One example from the .NET Base Class Library (BCL) is Control.CreateControlsInstance, which is is used by many other members of the (Windows Forms) Control class.

You can override this protected method to provide your own collection of controls, e.g. when you are implementing a custom control.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736