How to implement Factory Pattern using C#

This article focuses on the examination of Factory pattern and their use in the Microsoft’s Framework. Factory pattern is one of the most commonly used design patterns of all times.

Problem Scenario

Let’s consider an example code which is generating multiple objects:

if(type ==A")
{
    myObject = new ClassA();
}
if(type == “B")
{
    myObject = new ClassB();
}

In above code, different objects are getting created based on different if conditions. But there are some issues,

  • The above code executes lots of new keywords which will raise the client code complexity and furthermore raise maintenance. If one or more condition will be added, then one more new keyword will be required.
  • If one more class is required to instantiate, then the client should be knowing that class too. And the client will come to know about all the concrete objects types.

What is Factory Pattern?

It manages the issue of creating objects without determining the correct class of object that is about to create. The key to this design pattern is to “Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. This pattern lets a class defer instantiation to subclasses.”

This Pattern simplifies object creation as it is a  type of Creational Design Pattern. The user just needs to supply an appropriate parameter to the object of the factory class, no worries for object creation. Client class is not able to see instantiation logic, they can just create the object. This pattern fully abstracts the creation and instantiation.

In the event that you are creating controller action methods, those strategies can turn out to be exceptionally “jumbled” or “cluttered”. if in that controller method your object is filled and the filling of that object takes up a lot of code and is complex, at that point move that code to a factory class so your controller strategy stays “Clean”. Utilizing a factory pattern can be a piece of “Clean” code programming. For detailed description, click here

Logical Model

Similarly, as with other designs patterns, there are endless varieties of the Factory design. Although most variations normally utilized a similar arrangement of essential performing artists like a customer, a factory, and a product. A client is an instance that requires an object of another instance for some reason. As opposed to making the product instance straightforwardly, the client designates this duty to the factory. Once called, the factory makes another object of the product, sending it back to the client. Put just, the client utilizes the factory to make an object of the product. Below figure demonstrates this sensible connection between these components.

Factory Pattern

Implementing Factory Pattern

  • Open visual studio and create a console application of any name.
  • Create an interface [mk_highlight text=”IDetail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] having one method defination. Here, [mk_highlight text=”Detail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”]. This pattern can be implemented with the help of both interface and abstract class depending upon the different situations. Here, the interface is also known as the Product. And the classes implementing this interface are also known as ConcreteProduct.                                                                                     Factory Pattern
  • Then, create two classes implementing the [mk_highlight text=”IDetail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] interface and its [mk_highlight text=”Detail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] method. Here, [mk_highlight text=”ClassA” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] and [mk_highlight text=”ClassB” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”].
  • Now, create a ‘Creator’ class of [mk_highlight text=”abstract” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] type and define a [mk_highlight text=”abstract” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] method of [mk_highlight text=”IDetail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] type.
  • Now, create a ‘Concrete Creator’ class which implements our ‘Concrete’ class. Here, [mk_highlight text=”FactoryImplementation” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] class is implementing [mk_highlight text=”Factory” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] class.Factory Pattern
  • Now, create a [mk_highlight text=”switch” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] case which takes the user input and return the object of the class accordingly. Here, whichever case matches the user input, a [mk_highlight text=”new” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] instance of class will be created and returned to the client.

Client Code implementation

In the image below, we have created a single object of [mk_highlight text=”FactoryImplementation” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] class. Then asked user to ‘Enter A or B’. Based on the user input, the [mk_highlight text=”FactoryMethod” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] will return an object and assign it to [mk_highlight text=”getObject” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] variable which is of type [mk_highlight text=”IDetail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”]. As both our classes have [mk_highlight text=”Detail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] methods (due to [mk_highlight text=”IDetail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] interface implementation), it can be called from [mk_highlight text=”getObject” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] variable as it now have the instance of the class.

Factory Pattern

Output

When user pressed ‘A’, instance of [mk_highlight text=”ClassA” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] has created and [mk_highlight text=”Detail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] method of [mk_highlight text=”ClassA” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] has invoked.

Factory Pattern

When user pressed ‘B’, instance of [mk_highlight text=”ClassB” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] has created and [mk_highlight text=”Detail” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] method of [mk_highlight text=”ClassB” text_color=”#520909″ bg_color=”#ffffff”  font_family=”Consolas”] has invoked.

Factory Pattern

This is how we wrapper the instantiation logic of classes from the client.

Source Code

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
  
namespace FactoryPattern 
{ 
    // Product class
    interface IDetail 
    { 
        void Detail(); 
    } 
    // Concrete Product class
    class ClassA : IDetail 
    { 
        public void Detail() 
        { 
            Console.WriteLine("Detail method from Class A"); 
        } 
    } 
    // Concrete Product class
    class ClassB : IDetail 
    { 
        public void Detail() 
        { 
            Console.WriteLine("Detail method from Class B"); 
        } 
    }
    // Creator class
    abstract class Factory 
    { 
        public abstract IDetail FactoryMethod(string className); 
    } 
    // Concreate creator class
    class FactoryImplementation : Factory 
    { 
        public override IDetail FactoryMethod(string className) 
        { 
            switch (className) 
            { 
                case "A": 
                    return new ClassA(); 
                case "B": 
                    return new ClassB(); 
                default: 
                    return new ClassA(); 
            } 
        } 
    } 
    // Client class
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Factory factory = new FactoryImplementation(); 
            Console.WriteLine("Enter A or B"); 
            IDetail getObject = factory.FactoryMethod(Console.ReadLine()); 
            getObject.Detail(); 
            Console.ReadLine(); 
        }

}

}

When to use?

  1. Subclasses figures out of what instances are to be created.
  2. Parent class permits defer instantiation to subclasses, which means, if required, the object will create.
  3. The procedure of object creation should incorporate inside the application.
  4. A creator class won’t recognize what classes are need to create.

Conclusion

As we finish up this examination of the Factory design, it ought to be evident that this example offers significant advantages. From the abstraction of object creation to the utilization of immutable product and factory interfaces, this example gives a clear outline to design a versatile system which is fairly adaptable. The incorporation of this example in the .NET Framework is a clear demonstration of it convenience. Regardless of the idea of your application, this example can enable it to climate the undeniable trends.

Leave a Comment