Junior — Middle
Can you explain the principle of the Factory pattern and its main purpose?
sobes.tech AI
Answer from AI
The Factory pattern is designed to create objects without specifying the exact class of the object that will be created directly. The main idea is to delegate the creation of objects to a special method or class.
This allows:
- Isolating the object creation code from their usage.
- Easily changing the type of created objects without modifying client code.
- Simplifying the addition of new object types.
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:
return None
# Usage
animal = AnimalFactory.create_animal("dog")
print(animal.speak()) # Outputs: Woof
Thus, the client code does not depend on specific animal classes but works through the factory.