Factory patterns are types of Creational Patterns which can be used to instantiate objects freeing client programs from object creation tasks. Some of the typical reasons and scenarios to use a factory pattern can be:
- Separate object creation from the client.
- Separate object creation from decision of which object to create.
- Add new functionality without breaking the Open-Closed Principle.
- Have an ability to store information of an object to be created outside (config, database, settings) of code. (please refer Factory Pattern Instantiations)
Now, there is nothing like a Factory Pattern in the book “Design Patterns: Elements of Reusable Object-Oriented Software” by the Gang of Four. They talk about Factory Method and Abstract Factory patterns. We will come to those and more, but first lets consider a scenario depicted below.

We have an application/s for a multi-car sales and service agency. The agency currently deals in only 2 car brands BMW and Audi. As a car sales or service order is raised, the application needs to create a car object of the required type. A very straight forward way of doing this is to have an if/ else or switch case in the client code and create the required object.

In the above code the method GetCar is a part of the client code. This is simple and works but there are a few issues:
- As we can see, if the agency starts dealing with a new car brand, the above client code will have to be modified, thus violating the Open Closed Principle.
- The code is not very extensible. Consider a scenario where the agency has 2 different applications for sales and service. What happens then? The entire code will have to be replicated, any change has to be done at multiple places.
- Also, the approach is not very testable.
This is where factory patterns can help. Let’s look into the possible factory solutions.
Simple Factory Pattern
A simple factory encapsulates the object creation and hides it from the client. Consider the code below:

( The sample factory implementations in this post can be found in my Github.)
In this code, on the left, is the new CarFactory. As you can see, this is nothing but refactoring the original code to move the ICar object creation in a new class/ factory. On the right is the client code (in this case a console app). Lets discuss what this little refactoring has and hasn’t achieved.
- This simple factory has encapsulated the object creation, thus removing this task from the client code. This means that if a new car brand is added the client code needs no change, thus not violating the Open Closed Principle.
- Also, different client applications (sales, service, etc.) can use the same factory, thus any change required will be made only to the factory and no client application will be modified.
- The factory does not implement an interface. This can make it less extensible and testable.
- The client code needs to know which factory to instantiate.

Factory Method Pattern
The Gang of 4 defines Factory Method pattern as “This pattern defines an interface for creating an object, but let sub-classes decide which class to instantiate. Factory Method lets a class defer instantiation to sub-classes.”
What this means is that factory classes will derive from an abstract type (interface/ abstract class). I have mentioned factory ‘classes’ here as for each type of object we want there will be a separate factory and each of this factory will derive from an abstract factory type. It is like adding a level of abstraction to the simple factory.
In our case, we will have separate factories for instantiating BMW and Audi classes and both of them will derive from ICarFactory interface.

As we can see, we have separate BMWFactory and AudiFactory for BMW and Audi respectively and both these factories implement ICarFactory which defines the factory method GetCar. Some points to note:
- ICarFactory provides an abstraction to concrete factories and defines the method that concrete factories should implement for creating a car.
- Each car type has its own factory. This gives flexibility to perform class specific actions during class instantiation. In our case, BMW has a requirement of setting the model of a new car to “i8” by default, whereas Audi doesn’t have any such requirement. This can be easily achieved with factory method.
- In addition to the advantages that a simple factory gives, factory method is easily testable, extensible. It also satisfies the Dependency Injection Principle. The factories can be inherited to provide more specific initialisation. For e.g. Audi has hybrid cars, petrol cars and diesel cars. Each of these car types can have their own factories derived from the AudiFactory. But with all this inheritance comes the added complexity.
- Our client is a simple console app and so we are directly initialising a new BMWFactory instance. In actual it can be done using settings or config like DbFactory or Asp.NET Membership Providers.

One other way of implementing factory method pattern is using an abstract base class for factory classes instead of an interface. In our case we will use AbstractCarFactory.

Some points to note:
- Consider that the interface ICar has new method SetId which must be called on every new object creation of derived classes (BMW, Audi).
- Above we saw how the factory method with individual factory classes can take care of specific instantiation tasks. However, the SetId method is common to both BMW and Audi and can be called at a single place.
- To achieve this we replaced the ICarFactory with an abstract class AbstractCarFactory which exposes a method CreateCar, which in turn calls the GetCar method of implementing factories to get ICar and then calls SetId.
- This gives our factory method implementation an ability to handle common tasks at a single place.
Abstract Factory Pattern
The Gang of 4 defines Factory Method pattern as “Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”
What this means is the factory interface defines method/s to create objects which in turn may be related to or made up of other types of objects. Also, the concrete classes of the types to be created or the related types should never be specified. To understand this better, let us try to apply this to our car agency example.
Now, a car is made up of many parts. Let us consider just 2 of them: engine and doors, and define interfaces and classes for them.

Now, let us modify our ICar interface and Audi and BMW classes to show their association with IEngine and IDoors. Also, we will have 3 specific types of BMW classes representing 3 different models. To ensure that we have a specific model of BMW and no general BMW object, we mark BMW class as abstract.

As we can see here, we have 3 different classes for 3 different models of BMW and each model class knows the type of engine, doors and model name that it represents. In case of Audi, the single class Audi will create different types of models and hence requires IEngine and IDoors as input. The aim of having 2 different structures is just to show 2 different ways of implementation. Now, let us add an interface for the factory classes and the factory classes themselves.

Here, the interface ICarAbstractFactory defines methods to get 3 different types of cars and AudiFactory and BMWFactory have their own implementations of ICarAbstractFactory. Some points to note:
- Now the factories are creating different types of concrete products (ICar, IEngine, IDoors) and the concrete classes of none of them are exposed to the client.
- Each product of a factory is actually a composite made of different types. Thus we can say that an abstract factory implements composition and returns composite objects. This is one of the biggest advantages of abstract factory pattern.
- Each factory has more than 1 factory method. This is not binding and instead of 3 methods, ICarAbstractFactory can have a single GetCar method which takes an argument of type of the car to create. Audi and BMW factories can then implement some if-else logic to create the required car.
- This pattern helps in maintaining the Open Closed Principle.
- The decision of which concrete classes to instantiate is made by specific classes.
- The entire object creation can be hidden by making the constructors internal.

Comparison – Factory Method and Abstract Factory
- Factory method creates a single object whereas abstract factory creates a family of related products.
- Factory method uses simple inheritance, whereas abstract factory uses composition.
- Factory method abstracts the way objects are created whereas abstract factory can abstract the way factories are created. In a way abstract factory is 1 level up in terms of abstraction. Abstract factories can have factory method to create objects. In our case Audi and BMW factories can implement their own factory methods to create objects like specific car models.
Real life example – .Net DbProviderFactory
The most famous example in .Net of factory implementation is the DbProviderFactory/ DBProviderFactories. They are part of Ado.Net and are contained in System.Data.Common namespace.

The DbProviderFactories implement Simple Factory Pattern and returns a DbProviderFactory object based on the passed provider invariant name. DbProviderFactory implements Abstract Factory Pattern and creates various objects. Please look at the simplified class diagram below.

Conclusion
We have seen the different types of factory patterns, their implementations and advantages. Below are a few points on the usage of these patterns:
- Use factory patterns when you have a case of instantiating related objects or families of objects.
- Use simple factory when object initialisation are simple. We can have an interface for our simple factory class to make it more conforming to the SOLID principles.
- Use factory method when object initialisation is complex and each class has its own object initialisation requirements. Also, this pattern is more convenient when the class to instantiate is mentioned in an external store (settings, database, config).
- Use abstract factory, in addition to scenarios valid for factory method, in scenarios where the factory output are multiple objects or an object that is a composition of objects (family of objects).
Note
- The sample factory implementations in this post can be found in my Github.
- To know about different factory instantiation techniques please refer Factory Pattern Instantiations.
One thought on “Factory Patterns in C#”