Factory Method

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

Design Patterns: Elements of Reusable Object-Oriented Software

A factory method is a method which creates and returns an object. I think this is quite simple, and there are countless examples in the .NET Framework for it. What is it good for? Well, it enforces encapsulation. You have a method to create objects, and it’s far more flexible than just instantiating them through constructors.

The key players in this pattern are:

  • Creator: the abstract base class, which declares the factory method, which returns a type of Product.
  • ConcreteCreator: a concrete implementation of the Creator class, which overrides the factory method in it.
  • Product: the abstract base class or interface for your product types, what creator returns.
  • ConcreteProduct: the concrete implementation of the base Product class, what the ConcreteCreator classes return.

A common practice in the Factory Method pattern is to let the method accept a member of an enumeration, and based on the passed member, return different kinds of objects. Also, it’s quite common to make the constructor of the ConcreteProduct class private, thus enforcing clients to use the factory method.

Continue reading “Factory Method”