Sobes.tech
Junior — Middle

Which design patterns reflect the principles of SOLID?

sobes.tech AI

Answer from AI

The SOLID principles are aimed at creating flexible and maintainable architecture. Some design patterns that reflect these principles:

  • Single Responsibility Principle (SRP) — the "Facade" pattern helps to divide a complex system into separate parts with a single responsibility.

  • Open/Closed Principle (OCP) — the "Strategy" and "Decorator" patterns allow extending functionality without modifying existing code.

  • Liskov Substitution Principle (LSP) — the "Template Method" pattern ensures proper inheritance and substitutability of subclasses.

  • Interface Segregation Principle (ISP) — using interfaces with narrow specialization, for example, through the "Adapter" pattern.

  • Dependency Inversion Principle (DIP) — the "Dependency Injection" pattern allows depending on abstractions rather than concrete implementations.

Example in Python using the strategy pattern for OCP:

from abc import ABC, abstractmethod

class PaymentStrategy(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

class CreditCardPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Paying {amount} with a credit card")

class PayPalPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Paying {amount} via PayPal")

class Order:
    def __init__(self, payment_strategy: PaymentStrategy):
        self.payment_strategy = payment_strategy

    def checkout(self, amount):
        self.payment_strategy.pay(amount)

order = Order(CreditCardPayment())
order.checkout(1000)