Sobes.tech
Junior — Middle

Explain the working principle and purpose of the 'factory' pattern in object-oriented programming.

sobes.tech AI

Answer from AI

The "Factory" pattern is used to create objects without specifying the exact class of the object being created. Its main purpose is to encapsulate the object creation logic, which simplifies code extension and maintenance.

Working principle:

  • The client calls a factory method or class that returns an object of an interface or base class.
  • The factory decides which specific class to instantiate, hiding the details from the client.

Example in C#:

// Product interface
interface IAnimal {
    void Speak();
}

// Concrete products
class Dog : IAnimal {
    public void Speak() => Console.WriteLine("Woof");
}
class Cat : IAnimal {
    public void Speak() => Console.WriteLine("Meow");
}

// Factory
class AnimalFactory {
    public static IAnimal CreateAnimal(string type) {
        return type switch {
            "dog" => new Dog(),
            "cat" => new Cat(),
            _ => throw new ArgumentException("Unknown animal type")
        };
    }
}

// Usage
var animal = AnimalFactory.CreateAnimal("dog");
animal.Speak(); // Outputs "Woof"

This approach makes it easier to add new object types without changing client code.

Explain the working principle and purpose of the… - sobes.tech