How to use Factory Method Design Pattern in C#

The factory concept is probably the most common design patterns and recurs throughout the object-oriented programming. You will find countless references and uses of the factory pattern within the .net core foundational libraries and throughout the .net framework source code, most notable and probably one of the most commonly used factories can be found in the System.Data.Common namespace and the DbProviderFactories.

In this post we’ll explore the Factory Method pattern in detail by implementing a Trivial example and then we will explore a typical example of how the factory method pattern is implemented in a software application.

Code available on Github

The factory method design pattern falls under the Creational Design Patterns of Gang of Four (GOF) Design Patterns, and is most commonly used to create objects.

What is the Factory Method Pattern

The factory method pattern is a clever but subtle extension to the concept that a class acts as a traffic cop and decides which sub class of a single hierarchy will be instantiated.

In the factory pattern, developers create an object without exposing the creation logic. An interface is used for creating an object, but lets subclass decide which class to instantiate. Rather than defining each object manually, developers can do it programmatically.

In short, a factory is an object that creates objects without the use of a constructor.

The pattern does not actually have a decision point where one subclass is directly selected over another class. Instead, programs written to this pattern usually define an abstract class that creates objects but lets each subclass decide which object to create.

Factory Method Pattern: Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

The Factory Method Pattern, is slightly different from the Simple Factory Pattern, which enables the creation objects without exposing the instantiation logic to the client.

The Factory Method Pattern defines an interface for creating objects, but let subclasses to decide which class to instantiate.


When to use a Factory Method

The are a number of circumstances when developing an application when making use of the Factory Method is suitable. These situation include :

  • A class can’t anticipate which class objects it must create
  • A class uses its subclasses to specify which objects it creates
  • You need to localize the knowledge of which class gets created

It’s generally a bad idea for base classes to know about their derivatives. To fix this, we should use the ABSTRACT FACTORY pattern

A Typical situation maybe when a constructor needs to return an instance of type within which it resides, a factory method is able to return many different types of objects, all which belong to the same inheritance hierarchy.

Featured Book Review


How to implement Factory Pattern

We’ll develop a factory method that enables the creation of a vehicle depending on the number of wheels required

Factory Method Pattern

A vehicles can consist of any number of wheels, as an example, in a game when character needs to build a vehicle when they have set number of wheels.

If we pass the number of Wheels to our factory method it will build the vehicle and return it.

We’ll keep this example trivial so we don’t get lost in the detail, so we will define a simple interface of IVEHICLE which is nothing more than empty interface.
We’ll also Define 4 classes which will Inherit the IVehicle interface. Unicycle, MotorBike, Car and Truck.

We can now create a VechicleFactory class with a build method to create a vehicle depending on the number of wheels supplied.

We can now develop our little game, in this example it will be a Console Application, and we’ll ask the user to enter a number of wheels and then we’ll tell them what type of Vehicle they built.

If you start the Console Application, you’ll be asked a question to enter a number between 1 and 12 and a vehicle will be created depending on the number of wheels supplied.


Real World Implementation of Factory Pattern

This is obviously a very trivial example of a Factory Method just in order to put a point across, as to how to actually use them.
If you’re looking for a more complex implementation of a Factory Method pattern, take a look at the source code of my Threenine.Map application, and more specifically the class I have cunningly named the MapConfigurationFactory.

You’ll notice that this class, is basically the main brain of the application and is responsible for building and loading all the mapping configurations that have been defined within the application.
The factory has a number of entry points defined, but the main method I always use is the Scan method, which ultimately is the Abstract Factory Method.

The library itself contains just 3 interfaces ICustomMap, IMapFrom, IMapTo , which enable developers to implement various mapping logic and associate it with the POCO or Entity classes it relates too. For detailed explanation to how it works check out the documentation.

In brief what the MapConfigurationFactory does, it uses reflection to iterate through all the libraries contained in an assembly and retrieves all the classes have been marked with any of the interfaces and loads the Mappings to the Automapper – a Convention-based object-object mapper.


Conclusion

The Factory Method pattern, in my opinion is one of the most important patterns to understand within software development. It’s the one pattern that in all likelihood that you’ll most often implement. factory design pattern, is used to instantiate objects based on another data type. Factories are often used to reduce code bloat and make it easier to modify which objects need to be created.

Gary Woodfine

Freelance Full Stack Developer at threenine.co.uk
Helps businesses by improving their technical proficiencies and eliminating waste from the software development pipelines.

A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.

Latest posts by Gary Woodfine (see all)

Affiliate Disclaimer

Disclosure: Please note that some of the links included in the blog posts are affiliate links, which means I will earn a commission if you decide to make a purchase.

I only include affiliate links to products, services and companies that I have personal experience and have actually used. I only recommend them because they are helpful and useful, not because of the small commissions I make if you decide to buy something.

Please do not spend any money on these products unless you feel they are relevant, suitable and will help you achieve your goals.

Buying anyone of these products and the commisions earned will not make me an overnite multi millionaire, but they will help to cover the hosting costs and compensate for the countless hours and effort I put in to create meaningful and valuable free content I provide to help others succeed.

You've also undoubtedly noticed that I also use various advertising networks - unless of of course you're using an Ad blocker, this is also an attempt to reduce my monthly deficit I experience in providing free relevant, valuable and on occassion insightful content for the benefit of others.

I only really make some money if people click on the ads, unless of course you consider 1c per 1000 impressions real money!

Bear in mind just how many impressions I need to make before I can cover my £20 hosting costs a month!

If you are using an adblocker and guilt stricken you can of course donate using any of the buttons below, but I won't be holding my breath.


Buy me a coffeeBuy me a coffee
π