依赖倒置原则(Dependency Inversion Principle, DIP)

设计模式 设计模式
📅 2025-07-24 11:45 👤 admin

  1. 高层模块不应依赖低层模块,二者都应依赖抽象。
  2. 抽象不应依赖细节,细节应依赖抽象。
    示例
    # 反例:高层模块依赖低层模块
    class LightBulb:
        def turn_on(self):
            print("灯泡亮了")
    
    class Switch:
        def __init__(self):
            self.bulb = LightBulb()  # 直接依赖具体实现
    
    # 正例:依赖抽象
    from abc import ABC, abstractmethod
    
    class Switchable(ABC):
        @abstractmethod
        def turn_on(self):
            pass
    
    class LightBulb(Switchable):
        def turn_on(self):
            print("灯泡亮了")
    
    class Fan(Switchable):
        def turn_on(self):
            print("风扇转了")
    
    class Switch:
        def __init__(self, device: Switchable):
            self.device = device  # 依赖抽象而非具体实现