-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfactory_method.py
More file actions
97 lines (63 loc) · 1.99 KB
/
factory_method.py
File metadata and controls
97 lines (63 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""
Factory Method Design Pattern
The Factory Method pattern provides an interface for creating objects,
but lets subclasses decide which class to instantiate.
Use cases:
- When you don't know the exact types of objects at compile time
- When you want to provide a library of products and expose only interfaces
- When you want to extend your code with new products easily
"""
from abc import ABC, abstractmethod
# Product interface
class Animal(ABC):
"""Abstract product class."""
@abstractmethod
def speak(self):
"""Make the animal speak."""
pass
# Concrete products
class Dog(Animal):
"""Concrete product: Dog."""
def speak(self):
return "Woof!"
class Cat(Animal):
"""Concrete product: Cat."""
def speak(self):
return "Meow!"
class Duck(Animal):
"""Concrete product: Duck."""
def speak(self):
return "Quack!"
# Creator interface
class AnimalFactory(ABC):
"""Abstract creator class."""
@abstractmethod
def create_animal(self):
"""Factory method to create an animal."""
pass
def get_animal_sound(self):
"""Use the factory method."""
animal = self.create_animal()
return animal.speak()
# Concrete creators
class DogFactory(AnimalFactory):
"""Concrete creator: Dog factory."""
def create_animal(self):
return Dog()
class CatFactory(AnimalFactory):
"""Concrete creator: Cat factory."""
def create_animal(self):
return Cat()
class DuckFactory(AnimalFactory):
"""Concrete creator: Duck factory."""
def create_animal(self):
return Duck()
# Example usage
if __name__ == "__main__":
# Using factory methods
dog_factory = DogFactory()
print(f"Dog says: {dog_factory.get_animal_sound()}")
cat_factory = CatFactory()
print(f"Cat says: {cat_factory.get_animal_sound()}")
duck_factory = DuckFactory()
print(f"Duck says: {duck_factory.get_animal_sound()}")