Factory Design Pattern With .Net Core

What is Design Pattern?

In Software Development, design patterns are used in order to solve common architectural problems when designing an application or system. They must be used carefully and in the right situations for the right reasons.
If used correctly, design patterns may save developers a lot of time because they offer simple algorithms in order to solve complex problems. But, if not used correctly, they can bring a huge boost of complexity to your project, increasing the difficulty to solve the problem. It is crucial to understand design patterns and their behavior in order to use their biggest advantages.
Design patterns are organized into three main groups, as follows,
  1. Creational, focused to solve problems regarding objects creation mechanisms;
  2. Structural, creating a stable structure by design relationship between entities;
  3. Behavioral, improving objects behavior applying patterns on how they should communicate;

Benefits of using Design Patterns

  • Increased maintainability, with standardized algorithms;
  • Easy to apply, solving complex problems with best practices' solutions;
  • More efficiency, needing to do more with less code.

What is the Factory Design Pattern?

The factory design pattern is a very common design pattern, used in most of the software development projects. 
Factory Design 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. The factory method is used to create the objects instead of using their constructors, so you may have all the algorithm to define which object should be returned in this factory method instead of having to re-write these algorithms every time that you need to instantiate this object.

Why use Factory Design Pattern?

The main benefit of using the factory pattern is that you have your logic to create those objects in a unique single place, not having to replicate it every time you are going to instantiate those objects. Saying that we have, among others, those benefits:
  • Having a cleaner code, with business rules applied in a single place;
  • Hidden logic, without any exposure to the object creation logic to the client;
  • Increased maintainability, being able to change the factory results and behavior without affecting existent code.

Implementation Step by Step With .Net Core

The use case
In this example, we are going to have a C# with .Net Core Console Application responsible to select the best vehicle according to the provided number of passengers. The factory method will hold the logic to determine which is the vehicle, having the number of passengers as input, and returning the vehicle.
We have a car with up to 5 passengers, a bus up to 50 passengers, and a boat up to 150 passengers. The user provides the number of passengers that are going for this ride.

The Vehicle class that will be used as base for the others
  1. public abstract class Vehicle  
  2. {  
  3.     internal int capacity;  
  4.     public string GetData()  
  5.     {  
  6.        return this.GetType().ToString().Split(".")[1];  
  7.     }  
  8.     public int GetCapacity()  
  9.     {  
  10.        return capacity;  
  11.     }  
  12.     public void AddPassengers(int passengers)  
  13.     {  
  14.         if (capacity < passengers)  
  15.         {  
  16.             throw new Exception(this.GetData() +" reached max capacity");  
  17.         }  
  18.         else  
  19.             capacity -= passengers;  
  20.     }  
  22. }  
Car, boat and Bus classes that inherit from the vehicle class. 
  1. public class Boat: Vehicle  
  2. {  
  3.     public Boat()  
  4.     {  
  5.         base.capacity = 150;  
  6.     }  
  7. }  
  8. public class Bus: Vehicle  
  9. {  
  10.     public Bus()  
  11.     {  
  12.         base.capacity = 50;  
  13.     }  
  14. }  
  15. public class Car : Vehicle  
  16. {  
  17.     public Car()  
  18.     {  
  19.         base.capacity = 5;  
  20.     }  
  21. }  
Factory Class
The class that will have the creation logic, used to create the objects according to the user input.
  1. public class VehicleCreator  
  2. {  
  3.     public static Vehicle GetVehicle(int passengers)  
  4.     {  
  5.         if (passengers <= 5)  
  6.             return new Car();  
  7.         else if (passengers > 5 && passengers <= 50)  
  8.             return new Bus();  
  9.         else  
  10.             return new Boat();  
  11.     }  
  12. }  
Client code
The code running in the client, without exposing the creation logic.
  1. static void Main(string[] args)  
  2. {  
  3.     Console.WriteLine("Hello. How many passengers do you need?");  
  4.     int passengers = Convert.ToInt32(Console.ReadLine());  
  5.     var vehicle = VehicleCreator.GetVehicle(passengers);  
  6.     vehicle.AddPassengers(passengers);  
  7.     Console.WriteLine("Vehicle Type: " + vehicle.GetData() + ". With left capacity of: " + vehicle.GetCapacity());  
  8. }  
Congratulations, you have successfully applied the Factory Design Pattern using C# with .Net Core.