Python
Factory
Learn the Factory pattern.
Factory
The Factory pattern creates instances of different classes based on a parameter. The client calls a function without knowing which class will be used.
class Dog:
def speak(self):
return "hav"
class Cat:
def speak(self):
return "miyav"
def animal_factory(kind):
if kind == "dog":
return Dog()
if kind == "cat":
return Cat()
raise ValueError("bilinmeyen")
The Factory adds a layer between the client and the concrete class; adding a new type requires only one line of change.
Adding a new type
Adding a new type to the Factory is easy: define a new class and add a branch to the factory function. The client code does not change.
class Bird:
def speak(self):
return "cik"
def animal_factory(kind):
# ... existing branches
if kind == "bird":
return Bird()
This supports the open-closed principle: classes are open for extension, closed for modification.
Exercise Write an animal factory
Define class Dog: and class Cat:; add def speak(self): to each (Dog returns "hav", Cat returns "miyav"). Write def animal_factory(kind):: if kind == "dog": return Dog(), if kind == "cat": return Cat(), else raise ValueError("bilinmeyen"). Get an instance with a = animal_factory("dog"). Print the speak output with print(a.speak()).
Show example solution
class Dog:
def speak(self):
return "hav"
class Cat:
def speak(self):
return "miyav"
def animal_factory(kind):
if kind == "dog":
return Dog()
if kind == "cat":
return Cat()
raise ValueError("bilinmeyen")
a = animal_factory("dog")
print(a.speak())
Test yourself
-
Complete the factory call
def animal_factory(kind):
if kind == "dog":
return ____()
if kind == "cat":
return Cat()
Show answer
def animal_factory(kind):
if kind == "dog":
return Dog()
if kind == "cat":
return Cat()
-
What is the advantage of the Factory pattern?
- It runs faster
- The client does not know the concrete class
- It uses less memory
- The code is shorter
Show answer
The client does not know the concrete class — The Factory decouples the client from the concrete class; this makes change easier.
-
Match the Factory concepts
- animal_factory
- Produces an instance
- kind parameter
- Sets the type
- Dog()
- Is a concrete instance
- ValueError
- Raised on unknown type
Next lesson: Strategy