Junior — Middle
Can you explain the essence of the 'Factory' pattern and its main advantages?
sobes.tech AI
Answer from AI
The "Factory" pattern is a creational design pattern that provides an interface for creating objects but allows subclasses to decide which class to instantiate. In other words, object creation is delegated to a separate method or class.
Main advantages:
- Allows creating objects without specifying the exact class, increasing flexibility and extensibility of the code.
- Simplifies replacing and adding new types of objects without changing client code.
- Reduces coupling between classes, improving support and testing.
Example in Python:
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
class AnimalFactory:
@staticmethod
def create_animal(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
else:
raise ValueError("Unknown animal type")
# Usage
animal = AnimalFactory.create_animal("dog")
print(animal.speak()) # Output: Woof