In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.
Product: This is an interface for creating the objects.
ConcreteProduct: This is a class which implements the Product interface.
Creator: This is an abstract class and declares the factory method, which returns an object of type Product.
ConcreteCreator: This is a class which implements the Creator class and overrides the factory method to return an instance of a ConcreteProduct.
class ConcreteProductA : Product
class ConcreteProductB : Product
abstract class Creator
public abstract Product FactoryMethod(string type);
class ConcreteCreator : Creator
public override Product FactoryMethod(string type)
case "A": return new ConcreteProductA();
case "B": return new ConcreteProductB();
default: throw new ArgumentException("Invalid type", "type");
- Subclasses figure out what objects should be created.
- Parent class allows later instantiation to subclasses means the creation of object is done when it is required.
- The process of objects creation is required to centralize within the application.
- A class (creator) will not know what classes it will be required to create.
When to use
- In class have a “type” and must switch(type) in progress. Create a Factory Pattern to avoid modify this class in the future (this class is Closed principle).
When not use
- Therefore, the main disadvantages are cluttering. In most cases you end up with huge files or with many small files.