Factory Method Design Pattern

 UML diagram
 sample code in C#


Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Frequency of use:   high

UML class diagram


    The classes and/or objects participating in this pattern are:

  • Product  (Page)
    • defines the interface of objects the factory method creates
  • ConcreteProduct  (SkillsPage, EducationPage, ExperiencePage)
    • implements the Product interface
  • Creator  (Document)
    • declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
    • may call the factory method to create a Product object.
  • ConcreteCreator  (Report, Resume)
    • overrides the factory method to return an instance of a ConcreteProduct.

sample code in C#

This structural code demonstrates the Factory method offering great flexibility in creating different objects. The Abstract class may provide a default object, but each subclass can instantiate an extended version of the object.

Show code

// Factory Method pattern -- Structural example

This real-world code demonstrates the Factory method offering flexibility in creating different documents. The derived Document classes Report and Resume instantiate extended versions of the Document class. Here, the Factory Method is called in the constructor of the Document base class.

Show code

// Factory Method pattern -- Real World example

This .NET optimized code demonstrates the same real-world situation as above but uses modern, built-in .NET features, such as, generics, reflection, object initializers, automatic properties, etc.

Show code

// Factory Method pattern -- .NET optimized

   Better Code 
   Better Career 
   Better Lifestyle 

Design Pattern
Framework 4.5

C# and VB.NET


  Gang of Four Patterns
  Head First Patterns
  Enterprise Patterns
  Multi-Tier Patterns

  Repository Pattern
  Unit-of-Work Pattern
  CQRS Pattern
  Active Record Pattern

  Model View Controller
  Model View Presenter
  Model View ViewModel

  SparkTM RAD Platform
  Art Shop MVC Application
  Much more...

Click here for details

-- Instant Access --
Instant Download