Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
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.
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.
using System; using System.Collections; // "Product" abstract class Product { } // "ConcreteProductA" class ConcreteProductA : Product { } // "ConcreteProductB" class ConcreteProductB : Product { } // "Creator" abstract class Creator { // Methods abstract public Product FactoryMethod(); } // "ConcreteCreatorA" class ConcreteCreatorA : Creator { // Methods override public Product FactoryMethod() { return new ConcreteProductA(); } } // "ConcreteCreatorB" class ConcreteCreatorB : Creator { // Methods override public Product FactoryMethod() { return new ConcreteProductB(); } } /// <summary> /// Client test /// </summary> class Client { public static void Main( string[] args ) { // FactoryMethod returns ProductA Creator c = new ConcreteCreatorA(); Product p = c.FactoryMethod(); Console.WriteLine( "Created {0}", p ); // FactoryMethod returns ProductB c = new ConcreteCreatorB(); p = c.FactoryMethod(); Console.WriteLine( "Created {0}", p );
} }
Output
Created ConcreteProductA Created ConcreteProductB
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.