Exploring the Factory Method Design Pattern
Arifuzzaman Tanin
Software Engineer | C# | .NET | React | Blazor | JavaScript | Full Stack | Azure | DevOps | Agile | Microservices | gRPC
The Factory Method is a design pattern that falls under the category of creational design patterns. It provides a way to create objects without specifying their exact class. Instead of directly calling a constructor to create an object, the Factory Method pattern defines an interface or an abstract class for creating objects, and lets the subclasses decide which class to instantiate.
In simpler terms, the Factory Method pattern encapsulates the object creation logic and delegates the responsibility of creating objects to its subclasses. It provides a common interface for creating objects, but the actual class of the object is determined by the subclass implementation.
Here's a step-by-step breakdown of the Factory Method pattern:
By using the Factory Method pattern, you can achieve loose coupling between the client code and the specific classes being instantiated. It allows for flexibility and extensibility, as new subclasses can be added without modifying the client code. Additionally, it promotes the Single Responsibility Principle by separating the object creation logic from the client's code.
领英推荐
Here's an example code snippet in C# to illustrate the concept:
public interface SubscriptionPlan
{
? ? public void DisplaySelectedPlan();
}
public class PlatinumPlan : SubscriptionPlan
{
? ? public void DisplaySelectedPlan()
? ? {
? ? ? ? Console.WriteLine("Platinum plan is selected");
? ? }
}
public class DiamondPlan : SubscriptionPlan
{
? ? public void DisplaySelectedPlan()
? ? {
? ? ? ? Console.WriteLine("Diamond plan is selected");
? ? }
}
public class GoldenPlan : SubscriptionPlan
{
? ? public void DisplaySelectedPlan()
? ? {
? ? ? ? Console.WriteLine("Golden plan is selected");
? ? }
}
public class SubscriptionPlanFactory
{
? ? public static SubscriptionPlan SelectPlan(string type)
? ? {
? ? ? ? switch (type)
? ? ? ? {
? ? ? ? ? ? case "patinum":
? ? ? ? ? ? ? ? return new PlatinumPlan();
? ? ? ? ? ? case "diamond":
? ? ? ? ? ? ? ? return new DiamondPlan();
? ? ? ? ? ? case "golden":
? ? ? ? ? ? ? ? return new GoldenPlan();
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? throw new ArgumentException("Invalid plan type.");
? ? ? ? }
? ? }
}
public class Program
{
? ? public static void Main()
? ? {
? ? ? ? SubscriptionPlan subscription = SubscriptionPlanFactory.SelectPlan("patinum");
? ? ? ? subscription.DisplaySelectedPlan();
? ? }
}
The Factory Method pattern offers several benefits, including:
Overall, the Factory Method pattern provides a structured approach to object creation, promoting modularity, flexibility, and maintainability in software design.