When we create any software on broad level then we need to use some design pattern. Today, I am going to demonstrate about Factory Design Pattern.
Factory Design Pattern is a part of creational pattern. Using factory design pattern, we can create instance of the class without exposing the logic to outer world. Sometimes it is required to create the instance of the class on the runtime and then we use factory design pattern. It is used to create decoupled system.
As name suggested “Factory”, it is used to create object of the required class when needed.
Real Time Example
Here I am going to take a real life example to demonstrate it very clearly. Let suppose there is company which manufactures two types of car, First one is “Suzuki” and other one is “Honda”.
I need to know the details of each car based on their name. I will only pass the name and it will give us all the required details of the particular car, so it can be achieved to create two simple classes.
The following code is for implementing the Factory Design Pattern:
- using System;
- namespace FactoryDesignPatternDemo
- {
- public interface ICar
- {
- void GetCarDetails();
- }
- public class SuzukiCar: ICar
- {
- public void GetCarDetails()
- {
- Console.WriteLine("This is Suzuki Car");
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- ICar mycar = new SuzukiCar();
- mycar.GetCarDetails();
- Console.ReadLine();
- }
- }
- }
But there is a problem, when company launch a new car, we need to modify the code and add new car as well as the logic to get details of the car. Let say 100 cars added in the list, so we need to write the login for 100 cars in the code.
When we use Factory Design Pattern, there is no worry about the logic, we need to write a new class for new car and add logic to create the instance of the class.
Let's suppose company added a new car “BMW” in the list so how can we add the logic in the code. For this to create the instance of the class, we only need to add the logic here.
- else if (carName == "BMW")
- {
- carFactory = new BMWCarFactory("11001", 160);
- }
Thanks for reading this article, hope you enjoyed it.