Factory Pattern - Design Pattern
- Posted on
- Asp .Net
- By Deepak Talwar
This approach is especially beneficial for object creation since it allows flexibility and extension when the precise kinds of objects to be created could change or have to be decided at runtime.
Problem: Creating objects directly can lead to tight coupling between client code and concrete classes, making it hard to adapt to changes or extend the system with new classes.
Solution: The Factory Pattern solves this by providing an interface to create objects without exposing their concrete implementations.
How: The Factory Pattern defines a factory class or method responsible for creating objects. Clients request objects from the factory using a common interface, allowing them to work with abstract types while leaving the concrete object creation to the factory.

Think of it like a real-world factory. You (the client code) don't directly create products (objects). Instead, you go to a factory (the factory class) and tell it what kind of product you need. The factory then takes care of creating the specific product for you, without you needing to know the exact details of how it's made.
// 1. Product Interface
public interface IShape
{
void Draw();
}// 2. Concrete Products
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a Circle");
}
}public class Square : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a Square");
}
}public class Triangle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a Triangle");
}
}
// 3. Creator Interface (or Abstract Class)
public abstract class ShapeFactory
{
public abstract IShape CreateShape(string shapeType);// An operation that uses the created shape
public void DrawShape(string shapeType)
{
IShape shape = CreateShape(shapeType);
shape.Draw();
}
}// 4. Concrete Creators
public class SimpleShapeFactory : ShapeFactory
{
public override IShape CreateShape(string shapeType)
{
switch (shapeType.ToLower())
{
case "circle":
return new Circle();
case "square":
return new Square();
case "triangle":
return new Triangle();
default:
throw new ArgumentException("Invalid shape type.", nameof(shapeType));
}
}
}// Client Code
public class Client
{
public static void Main(string[] args)
{
ShapeFactory factory = new SimpleShapeFactory();IShape circle = factory.CreateShape("circle");
circle.Draw(); // Output: Drawing a CircleIShape square = factory.CreateShape("square");
square.Draw(); // Output: Drawing a Squarefactory.DrawShape("triangle"); // Output: Drawing a Triangle
// try
// {
// IShape invalidShape = factory.CreateShape("pentagon"); // Throws ArgumentException
// }
// catch (ArgumentException ex)
// {
// Console.WriteLine(ex.Message);
// }
}
}
2
.
.