Python

""

Design Patterns - Elements of Reusable Object-Oriented Software 23 Creational PatternsStructural PatternsBehavioral Patterns

&
1
  • Factory Pattern
  • Abstract Factory Pattern
  • Singleton Pattern
  • Builder Pattern
  • Prototype Pattern
2
  • Adapter Pattern
  • Bridge Pattern
  • Filter / Criteria Pattern
  • Composite Pattern
  • Decorator Pattern
  • Facade Pattern
  • Flyweight Pattern
  • Proxy Pattern
3
  • Chain of Responsibility Pattern
  • Command Pattern
  • Interpreter Pattern
  • Iterator Pattern
  • Mediator Pattern
  • Memento Pattern
  • Observer Pattern
  • State Pattern
  • Null Object Pattern
  • Strategy Pattern
  • Template Method Pattern
  • Visitor Pattern
4
  • MVC Model-View-Controller Pattern
  • Business Delegate Pattern
  • Composite Entity Pattern
  • Data Access Object Pattern
  • Front Controller Pattern
  • Intercepting Filter Pattern
  • Service Locator Pattern
  • Transfer Object Pattern

[]

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

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")

  • Notification
  • EmailNotification SMSNotification
  • NotificationFactory

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 ")

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')

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("")