Factory Method Design Pattern - C#

19 Jan 2024
Intermediate
113K Views
8 min read  

Factory Method Design Pattern - C#: An Overview

The factory method design pattern abstracts the process of object creation and allows the object to be created at run-time when it is required. Factory method pattern falls under the Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is used to create objects. People usually use this pattern as the standard way to create objects. In this Design Pattern Tutorial, I would like to share what is factory pattern and how it works.

What is the Factory Method Pattern?

In the Factory pattern, we create the object without exposing the creation logic. In this pattern, an interface is used for creating an object but lets the subclass decide which class to instantiate. The creation of an object is done when it is required. The Factory method allows a class later instantiation to subclasses.

Factory Method Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the factory method design pattern is given below:
Factory Method Pattern

The classes, interfaces, and objects in the above UML class diagram are as follows:

  1. Product

    This is an interface for creating the objects.

  2. ConcreteProduct

    This is a class that implements the Product interface.

  3. Creator

    This is an abstract class and declares the factory method, which returns an object of type Product.

  4. ConcreteCreator

    This is a class that implements the Creator class and overrides the factory method to return an instance of a ConcreteProduct.

C# - Implementation Code

interface Product
{

}

class ConcreteProductA : Product
{
}

class ConcreteProductB : Product
{
}

abstract class Creator
{
 public abstract Product FactoryMethod(string type);
}

class ConcreteCreator : Creator
{
 public override Product FactoryMethod(string type)
 {
 switch (type)
 {
 case "A": return new ConcreteProductA();
 case "B": return new ConcreteProductB();
 default: throw new ArgumentException("Invalid type", "type");
 }
 }
}

This code demonstrates the Factory Method design pattern, in which a ConcreteCreator class determines which concrete Product type to construct based on input, separating object production from consumption.

Factory Method Pattern - Example

Factory Method Pattern

Who is what?

The classes, interfaces, and objects in the above class diagram can be identified as follows:

  1. IFactory - Interface

  2. Scooter & Bike - Create product classes

  3. VehicleFactory - Creator

  4. ConcreteVehicleFactory - Concreate Creator

C# - Sample Code

using System;
namespace Factory
{
 /// <summary>
 /// The 'Product' interface
 /// </summary>
 public interface IFactory
 {
 void Drive(int miles);
 }

 /// <summary>
 /// A 'ConcreteProduct' class
 /// </summary>
 public class Scooter : IFactory
 {
 public void Drive(int miles)
 {
 Console.WriteLine("Drive the Scooter : " + miles.ToString() + "km");
 }
 }

 /// <summary>
 /// A 'ConcreteProduct' class
 /// </summary>
 public class Bike : IFactory
 {
 public void Drive(int miles)
 {
 Console.WriteLine("Drive the Bike : " + miles.ToString() + "km");
 }
 }

 /// <summary>
 /// The Creator Abstract Class
 /// </summary>
 public abstract class VehicleFactory
 {
 public abstract IFactory GetVehicle(string Vehicle);

 }

 /// <summary>
 /// A 'ConcreteCreator' class
 /// </summary>
 public class ConcreteVehicleFactory : VehicleFactory
 {
 public override IFactory GetVehicle(string Vehicle)
 {
 switch (Vehicle)
 {
 case "Scooter":
 return new Scooter();
 case "Bike":
 return new Bike();
 default:
 throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
 }
 }

 }
 
 /// <summary>
 /// Factory Pattern Demo
 /// </summary>
 class Program
 {
 static void Main(string[] args)
 {
 VehicleFactory factory = new ConcreteVehicleFactory();

 IFactory scooter = factory.GetVehicle("Scooter");
 scooter.Drive(10);

 IFactory bike = factory.GetVehicle("Bike");
 bike.Drive(20);

 Console.ReadKey();

 }
 }
}

This code includes a Vehicle Factory that wraps vehicle production, allowing clients to access alternative vehicles (scooters or Bikes) without knowing their specific classes, promoting flexibility and loose coupling.

Output

Factory Pattern Demo Output

When to use it?

  1. Subclasses figure out what objects should be created.

  2. Parent class allows later instantiation to subclasses means the creation of an object is done when it is required.

  3. The process of objects created is required to centralize within the application.

  4. A class (creator) will not know what classes it will be required to create.

Read More Articles Related to Design Pattern
Summary

The factory method design pattern provides a flexible and centralized approach to object production. It separates clients from the creation process, allowing dynamic object instantiation based on runtime requirements. This pattern allows for clearer, more maintainable code and promotes loose coupling, making it an invaluable tool for developers.

FAQs

Q1. What is the Factory Method design pattern in C#?

The Factory Method is a creational design pattern that provides an interface for producing objects while allowing subclasses to specify the type of object to be created. If the superclass has a creation method and numerous subclasses that extend it, you're probably dealing with a factory method.

Q2. What type of design pattern is the Factory Method?

The Factory Method is a creational design pattern that provides an interface for producing objects in a superclass while allowing subclasses to specify the type of objects to be created.

Q3. Why is factory pattern used?

The factory design pattern gives a technique for coding for interfaces rather than implementations. The factory approach removes the actual implementation classes from the client code. The factory approach makes our code more durable, less connected, and easier to modify.

Q4. What is the difference between the MVC and factory patterns?

MVC is a high-level architectural paradigm that separates the UI from the model. Factory is a low-level pattern that is intended to create objects.

Q5. Where is the Factory Method used?

In object-oriented programming, the Factory Method is a Creational Design Pattern that allows us to generate objects without specifying which class will be instantiated. Instead of generating objects directly, we utilize a factory method to generate and return them.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Learn to Crack Your Technical Interview

Accept cookies & close this