Factory Method Design Pattern In C#

Introduction

In this article, we will solve a real-life problem using factory design pattern. The factory design pattern is the most popular design pattern in software development.

What is a factory method design pattern?

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method either specified in an interface and implemented by child classes or implemented in a base class and optionally overridden by derived classes rather than by calling a constructor.


Why use factory method design pattern

Factories and interfaces allow for a lot more long-term flexibility. Tern is used instead of the regular class constructor for keeping within the SOLID principle of programming, decoupling the construction of objects from the objects themselves.  It allows you to introduce an Inversion of Control (IoC) container easily. Read more

Factory design pattern kind of object factory. In the real world, we already heard the factory word. like food factory, machine factory etc. In OOP, factory is a collection of objects. where you can decide which object, we will get.

Business Problem

Now we will try to solve a business application problem using the factory design pattern.
suppose we have a shop and our customer bought a computer from this shop. We have connected 3 Computer Manufacturers company. Each company has a different service and warranty. If the customer faces any problem after buying a computer, we have to call the manufacturer based on their manufacturer company name. So, our main problem here creates our manufacturer object based on their company name. Here we will create a factory method. This factory helps us to create object.

Solution

Now focus on coding. Create a new console application project and name it FactoryPattern.





Next, create a new folder inside the FactoryPattern project then name it Companies.  Next, Create Interface Inside the Companies folder and name it ICompany.cs and put the following code in its

namespace Factory.Companies
{
    public interface ICompany
    {
        string DoWork();
    }
}

After that, we will create a class for a different type of company’s computer. Next, create a new class inside the Companies folder and name it AppleCompany.cs and put the following code in it

namespace Factory.Companies
{
    public class AppleCompany : ICompany
    {
        private string _name;
        public AppleCompany(string name)
        {
            _name = name;
        }
        public string DoWork() => $"object successfully created from {_name}";

    }
}

Next, create a new class inside the Companies folder and name it HPCompany.cs and put the following code in it

namespace Factory.Companies
{
    public class HPCompany : ICompany
    {
        private string _name;
        public HPCompany(string name)
        {
            _name = name;
        }
        public string DoWork() => $"object successfully created from {_name}";

    }
}

Next, create a new class inside the Companies folder and name it LenovoCompany.cs and put the following code in it

namespace Factory.Companies
{
    public class LenovoCompany : ICompany
    {
        private string _name;
        public LenovoCompany(string name)
        {
            _name = name;
        }
        public string DoWork () => $"object successfully created from {_name}";

    }
}

Then create a new folder and Name it Factory. Inside the Factory folder create a new interface name it IComputerFactory.cs and put the following code in it

using Factory.Companies;

namespace Factory.Factory
{
    public interface IComputerFactory
    {
        ICompany GetCompany(string name);
    }
}

Next, create a new class inside the Factory folder and name it ComputerFactory.cs and put the following code in it.

using Factory.Companies;
using System;

namespace Factory.Factory
{
    public class ComputerFactory : IComputerFactory
    {
        public ICompany GetCompany(string name)
        {
            switch (name)
            {
                case "apple":
                    return new AppleCompany(name);
                case "hp":
                    return new HPCompany(name);
                case "lenovo":
                    return new LenovoCompany(name);
                default:
                    throw new ApplicationException("unknown company");
            }
        }
    }
}

We have created our factory class successfully. Now we will try to test the factory method. Now go to the Program.cs and put the following code in it

using Factory.Factory;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Factory
{
    class Program
    {

        static void Main(string[] args)
        {
            var serviceProvider = ServiceProvider(); // Call Service Provider
            var factory = serviceProvider.GetRequiredService<IComputerFactory>(); // Resolve dependency

            //call factory
            var result_apple = factory.GetCompany("apple").DoWork(); // call factory for apple computer 
            Console.WriteLine(result_apple);
            
            var result_hp = factory.GetCompany("hp").DoWork(); //  call factory for hp computer
            Console.WriteLine(result_hp);

            var result_lenovo = factory.GetCompany("lenovo").DoWork(); //  call factory for lenovo computer
            Console.WriteLine(result_lenovo);
            
            Console.ReadLine(); 
        }

        //Setup IOC 
        public static ServiceProvider ServiceProvider()
        {
            var provider = new ServiceCollection()
             .AddSingleton<IComputerFactory, ComputerFactory>()
             .BuildServiceProvider();
            return provider;
        }
    }
}

The final project structure image below



Now run the application



We can see our factory design pattern working success.

Conclusion

We have successfully solved our business problem using Factory design pattern. Factory design pattern gives us better maintainability, better design and better control.


Source Code

Get the source code from GitHub

Post a Comment

0 Comments