Factory Method PatternCSE776-Design PatternsByAnjan Kumar BollamProfessor Jim Fawcett
Intent“Define an interface for creating an object, but let subclasses decide which class to instantiate”
It lets a class defer instantiation to subclasses at run time.
It refers to the newly created object through a common interface.Also Known asVirtual Constructor
The main intent of the virtual constructor idiom in C++ is to create a copy of an object or a new object without knowing its concrete type and this is exactly the Factory Method of initialization.Motivating ExamplesHotel: One good example for the Factory Method is the Hotel. When Check in, the person gets the key from the front desk where he can be looked up as the ‘room’ factory. Now if he wants to make a phone call to some outside office,  he will contact the front desk to make the connection to that call which means the front desk is acting as an interface.Motivating Examples - Cont.Frameworks:  It is used in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework since the library knows when an object needs to be created, but not what kind of object it should create, this being specific to the application using the library in the framework.Motivating Examples – Cont.
ForcesIt is required to have a set of reusable classes which are flexible enough to be extended.
The client does not know the type of object that need to be created in advance and still want to perform operations on them.ApplicabilityFactory Method is needed when:
A class can’t anticipate the class of objects it must create.
A class wants its subclasses to specify the objects it creates.
Localization of knowledge of helper sub classes which the classes want to delegate.Basic Structure
ParticipantsProduct(IHttpHandler)
Defines the interface of objects the factory method creates.
ConcreteProduct(ASP.SamplePage_aspx)
Implements the Product Interface
Creator(IHttpHandlerFactory)
Declares the factory method and may provide a default implementation for it.
It returns an object of type Product.
ConcreteCreator(PageHandlerFactory)
Overrides the factory method to return an instance of ConcreteProduct.CollaboratorsThe Creator relies on the subclass’s factory method and return instance of appropriate ConcreteProduct object.
The Creator executes some sequence of operations on the object.ConsequencesThe code deals with only with the product interface, therefore it can work with any user defined Concrete Product classes (decoupling subclass details from client classes).

Factory Method Pattern

  • 1.
    Factory Method PatternCSE776-DesignPatternsByAnjan Kumar BollamProfessor Jim Fawcett
  • 2.
    Intent“Define an interfacefor creating an object, but let subclasses decide which class to instantiate”
  • 3.
    It lets aclass defer instantiation to subclasses at run time.
  • 4.
    It refers tothe newly created object through a common interface.Also Known asVirtual Constructor
  • 5.
    The main intentof the virtual constructor idiom in C++ is to create a copy of an object or a new object without knowing its concrete type and this is exactly the Factory Method of initialization.Motivating ExamplesHotel: One good example for the Factory Method is the Hotel. When Check in, the person gets the key from the front desk where he can be looked up as the ‘room’ factory. Now if he wants to make a phone call to some outside office, he will contact the front desk to make the connection to that call which means the front desk is acting as an interface.Motivating Examples - Cont.Frameworks: It is used in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework since the library knows when an object needs to be created, but not what kind of object it should create, this being specific to the application using the library in the framework.Motivating Examples – Cont.
  • 6.
    ForcesIt is requiredto have a set of reusable classes which are flexible enough to be extended.
  • 7.
    The client doesnot know the type of object that need to be created in advance and still want to perform operations on them.ApplicabilityFactory Method is needed when:
  • 8.
    A class can’tanticipate the class of objects it must create.
  • 9.
    A class wantsits subclasses to specify the objects it creates.
  • 10.
    Localization of knowledgeof helper sub classes which the classes want to delegate.Basic Structure
  • 11.
  • 12.
    Defines the interfaceof objects the factory method creates.
  • 13.
  • 14.
  • 15.
  • 16.
    Declares the factorymethod and may provide a default implementation for it.
  • 17.
    It returns anobject of type Product.
  • 18.
  • 19.
    Overrides the factorymethod to return an instance of ConcreteProduct.CollaboratorsThe Creator relies on the subclass’s factory method and return instance of appropriate ConcreteProduct object.
  • 20.
    The Creator executessome sequence of operations on the object.ConsequencesThe code deals with only with the product interface, therefore it can work with any user defined Concrete Product classes (decoupling subclass details from client classes).
  • 21.
    New concrete classescan be added without recompiling the existing code.
  • 22.
    It may leadto many subclasses if the product objects requires one or more additional objects. (Parallel class hierarchy)Consequences – Cont.
  • 23.
  • 24.
    Abstract Creator classwith no default implementation
  • 25.
    Concrete Creator withdefault implementation.
  • 26.
  • 27.
  • 28.
    TemplatesParameterized Factory MethodsclassCreator {public: virtual Product* Create(ProductID id) { if (id == P1) return new MyProduct; if (id == P2) return new YourProduct; // other products ... return 0; }};// You can subclass the Creator to handle more IDsProduct* MyCreator::Create(ProductID id) { if (id == P3) return new TheirProduct; // Handle other IDs return this->Creator::Create(id);};
  • 29.
    Templatized Factory MethodsclassCreator {public: Creator() { // You cannot call the factory method here (why?) // Use lazy initialization instead } virtual Product* CreateProduct() = 0;};template <class T>class StandardCreator: public Creator {public: virtual Product* CreateProduct() { return new T; }}// In the ClientStandardCreator<MyProduct> myCreator;
  • 30.
    Known UsesIt isa very pervasive pattern.
  • 31.
    It is usedin several places in the Java API. For example, URLConnection has a method getContent that returns the content as an appropriate object (html, gif etc.)
  • 32.
    FCL (.Net FrameworkClass Library) is no exception to the use of Factory Method Pattern. For example, it is used in Systems.Collections.IEnumerable, System.Net.WebRequest, System.Security.CryptographyRelated PatternsAbstract Factory
  • 33.
  • 34.
  • 35.
    References Design Patterns, Elementsof Reusable Object-Oriented Software, Erich Gamma, et. al., Addison-Wesley, 1994,ISBN 0-201-63361-2
  • 36.
  • 37.