Repository navigation
Expand file tree
/
Copy pathclass_pattern.py
More file actions
105 lines (80 loc) · 2.43 KB
/
Copy pathclass_pattern.py
File metadata and controls
105 lines (80 loc) · 2.43 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
97
98
99
100
101
102
103
104
105
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b)
class Dog:
def speak(self):
return "woof"
class Cat:
def speak(self):
return "meao"
def animal_factory(animal='dog'):
"""Simple factory returning an animal instance.
The original implementation compared the provided ``animal`` name
using exact, case-sensitive matches (``'Dog'`` and ``'Cat'``) while the
default argument was ``'dog'``. As a result, calling the factory with
lowercase values like ``animal_factory('dog')`` returned ``None``.
The function now normalizes the input to lowercase and handles unknown
animal names explicitly.
"""
animal = animal.lower()
if animal == 'dog':
return Dog()
if animal == 'cat':
return Cat()
raise ValueError(f"Unknown animal: {animal}")
pet = animal_factory("Dog")
print(pet.speak())
# Builder pattern
class PizzaBuilder:
def __init__(self):
self.pizza = []
def add_cheese(self):
self.pizza.append("cheese")
return self
def add_pepporini(self):
self.pizza.append("peporini")
return self
def build(self):
return self.pizza
pizza = PizzaBuilder().add_cheese().add_pepporini().build()
print(pizza)
class PayByCard:
def pay(self, amount): print(f"Paying {amount} by card")
class PayByCash:
def pay(self, amount): print(f"Paying {amount} by cash")
class PaymentProcessor:
def __init__(self, strategy): self.strategy = strategy
def pay(self, amount): self.strategy.pay(amount)
payment = PaymentProcessor(PayByCash())
payment.pay(100)
def make_bold(func):
def wrapper(): return "<b>" + func() + "</b>"
return wrapper
@make_bold
def greet(): return "Hello"
print(greet()) # <b>Hello</b>
# Decorator pattern
def make_bold(func):
def wrapper(): return "<b>" + func() + "</b>"
return wrapper
@make_bold
def greet():
return "Hello"
print(greet())
class Subject:
def __init__(self): self.observers = []
def register(self, observer): self.observers.append(observer)
def notify_all(self, data):
for observer in self.observers:
observer.update(data)
class Observer:
def update(self, data): print(f"Received: {data}")
s = Subject()
s.register(Observer())
s.notify_all("New event!")