Python
""
Design Patterns - Elements of Reusable Object-Oriented Software 23 Creational PatternsStructural PatternsBehavioral Patterns
| & | ||
|---|---|---|
| 1 |
|
|
| 2 |
|
|
| 3 |
|
|
| 4 |
|
1Open-Closed Principle
2Liskov Substitution Principle
3Dependency Inversion Principle
4Interface Segregation Principle
5Law of Demeter
""
6Composite Reuse Principle
Python
Python
Singleton
class DatabaseConnection:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
print("")
return cls._instance
def connect(self):
print("")
#
db1 = DatabaseConnection()
db2 = DatabaseConnection()
print(f"db1 db2 {db1 is db2}") # True
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
print("")
return cls._instance
def connect(self):
print("")
#
db1 = DatabaseConnection()
db2 = DatabaseConnection()
print(f"db1 db2 {db1 is db2}") # True
Factory
from abc import ABC, abstractmethod
#
class Notification(ABC):
@abstractmethod
def send(self, message: str):
pass
#
class EmailNotification(Notification):
def send(self, message: str):
print(f"{message}")
class SMSNotification(Notification):
def send(self, message: str):
print(f"{message}")
#
class NotificationFactory:
@staticmethod
def create_notification(notification_type: str) -> Notification:
if notification_type == "email":
return EmailNotification()
elif notification_type == "sms":
return SMSNotification()
else:
raise ValueError("")
#
email = NotificationFactory.create_notification("email")
sms = NotificationFactory.create_notification("sms")
email.send("")
sms.send("123456")
#
class Notification(ABC):
@abstractmethod
def send(self, message: str):
pass
#
class EmailNotification(Notification):
def send(self, message: str):
print(f"{message}")
class SMSNotification(Notification):
def send(self, message: str):
print(f"{message}")
#
class NotificationFactory:
@staticmethod
def create_notification(notification_type: str) -> Notification:
if notification_type == "email":
return EmailNotification()
elif notification_type == "sms":
return SMSNotification()
else:
raise ValueError("")
#
email = NotificationFactory.create_notification("email")
sms = NotificationFactory.create_notification("sms")
email.send("")
sms.send("123456")
NotificationEmailNotificationSMSNotificationNotificationFactory
Observer
from abc import ABC, abstractmethod
#
class Observer(ABC):
@abstractmethod
def update(self, message: str):
pass
#
class EmailSubscriber(Observer):
def __init__(self, name: str):
self.name = name
def update(self, message: str):
print(f"{self.name} {message}")
class SMSSubscriber(Observer):
def __init__(self, name: str):
self.name = name
def update(self, message: str):
print(f"{self.name} {message}")
#
class NewsPublisher:
def __init__(self):
self._subscribers = []
def subscribe(self, subscriber: Observer):
self._subscribers.append(subscriber)
def unsubscribe(self, subscriber: Observer):
self._subscribers.remove(subscriber)
def notify_subscribers(self, message: str):
for subscriber in self._subscribers:
subscriber.update(message)
#
publisher = NewsPublisher()
#
alice = EmailSubscriber("Alice")
bob = SMSSubscriber("Bob")
#
publisher.subscribe(alice)
publisher.subscribe(bob)
#
publisher.notify_subscribers("Python 3.12 ")
#
publisher.unsubscribe(alice)
publisher.notify_subscribers(" Bob ")
#
class Observer(ABC):
@abstractmethod
def update(self, message: str):
pass
#
class EmailSubscriber(Observer):
def __init__(self, name: str):
self.name = name
def update(self, message: str):
print(f"{self.name} {message}")
class SMSSubscriber(Observer):
def __init__(self, name: str):
self.name = name
def update(self, message: str):
print(f"{self.name} {message}")
#
class NewsPublisher:
def __init__(self):
self._subscribers = []
def subscribe(self, subscriber: Observer):
self._subscribers.append(subscriber)
def unsubscribe(self, subscriber: Observer):
self._subscribers.remove(subscriber)
def notify_subscribers(self, message: str):
for subscriber in self._subscribers:
subscriber.update(message)
#
publisher = NewsPublisher()
#
alice = EmailSubscriber("Alice")
bob = SMSSubscriber("Bob")
#
publisher.subscribe(alice)
publisher.subscribe(bob)
#
publisher.notify_subscribers("Python 3.12 ")
#
publisher.unsubscribe(alice)
publisher.notify_subscribers(" Bob ")
Python
Python
Python
# Python
def create_payment(method):
payment_methods = {
'credit_card': CreditCardPayment,
'paypal': PayPalPayment,
'alipay': AlipayPayment
}
return payment_methods[method]()
#
payment = create_payment('alipay')
def create_payment(method):
payment_methods = {
'credit_card': CreditCardPayment,
'paypal': PayPalPayment,
'alipay': AlipayPayment
}
return payment_methods[method]()
#
payment = create_payment('alipay')
Python
def log_execution_time(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} {end - start:.2f}")
return result
return wrapper
@log_execution_time
def process_data(data):
#
import time
time.sleep(1)
return f"{data}"
#
result = process_data("")
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} {end - start:.2f}")
return result
return wrapper
@log_execution_time
def process_data(data):
#
import time
time.sleep(1)
return f"{data}"
#
result = process_data("")