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.

So many things can be said (and was said) about Factory Method, but I personally think it’s so straightforward that I wouldn’t like to waste time on its details.

Further Readings:

Factory Method pattern on Wikipedia

Design Patterns (book): pp 107-116

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s