Factory Pattern

Object creation patterns

Interview Relevant: Design patterns

Factory Pattern

Create objects without specifying exact class.

Code Examples

python
1class Dog:
2    def speak(self): return "Woof"
3
4class Cat:
5    def speak(self): return "Meow"
6
7def get_pet(type):
8    pets = dict(dog=Dog, cat=Cat)
9    return pets[type]() if type in pets else None
10
11pet = get_pet("dog")
12print(pet.speak())

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In