Sobes.tech
Junior — Middle

What is the role of the Factory design pattern and in what cases is it used?

sobes.tech AI

Answer from AI

The Factory design pattern is used to create objects without explicitly specifying the exact class of the object to be created. It encapsulates the object creation logic, allowing client code to work with abstractions rather than concrete implementations.

Main use cases:

  • When creating objects from a family of classes that implement a common interface.
  • When object creation is complex or requires additional logic.
  • To simplify maintenance and extension of code, enabling adding new object types without changing client code.

Example in C#:

public interface IShape {
    void Draw();
}

public class Circle : IShape {
    public void Draw() => Console.WriteLine("Drawing Circle");
}

public class Square : IShape {
    public void Draw() => Console.WriteLine("Drawing Square");
}

public class ShapeFactory {
    public IShape GetShape(string shapeType) {
        return shapeType.ToLower() switch {
            "circle" => new Circle(),
            "square" => new Square(),
            _ => null
        };
    }
}

// Usage
var factory = new ShapeFactory();
IShape shape = factory.GetShape("circle");
shape.Draw();

Thus, Factory simplifies object creation and enhances architecture flexibility.