导入
组合与设计灵活性
通过组合和委托,将简单的对象组合成更大的结构,学习构建复杂、模块化的应用程序。
1class Engine: 2 def __init__(self, horsepower): 3 self.horsepower = horsepower 4 5 def describe(self): 6 return f"{self.horsepower} HP Engine" 7 8class Vehicle: 9 def __init__(self): 10 # The Vehicle "has" an Engine. 11 # It takes responsibility for creating it. 12 self.engine = Engine(200) 13 14 def get_specs(self): 15 # Accessing the component to get data 16 engine_info = self.engine.describe() 17 print(f"Vehicle Specs: {engine_info}") 18 19# Usage 20my_car = Vehicle() 21my_car.get_specs()
1class Engine: 2 def start_up(self): 3 print("Engine: Fuel injection active. Pistons firing.") 4 5class Dashboard: 6 def boot_system(self): 7 print("Dashboard: GPS loaded. Radio ready.") 8 9class Vehicle: 10 def __init__(self): 11 self.engine = Engine() 12 self.dashboard = Dashboard() 13 14 def start(self): 15 print("Vehicle: Driver pressed start button.") 16 # Delegation: The vehicle coordinates, but components do the work 17 self.engine.start_up() 18 self.dashboard.boot_system() 19 print("Vehicle: Ready to drive.") 20 21# Usage 22suv = Vehicle() 23suv.start()
1class V8Engine: 2 def run(self): 3 print("V8 Engine: Roaring with gas power!") 4 5class ElectricMotor: 6 def run(self): 7 print("Electric Motor: Humming silently with battery power.") 8 9class Vehicle: 10 def __init__(self, engine): 11 # Dependency Injection: We assign the engine passed in from outside. 12 # The Vehicle doesn't care what type it is, as long as it fits. 13 self.engine = engine 14 15 def drive(self): 16 print("Vehicle: Engaging movement...") 17 self.engine.run() # Polymorphic delegation 18 19# Usage 20# 1. We build the components (dependencies) first 21gas_engine = V8Engine() 22battery_motor = ElectricMotor() 23 24# 2. We inject them into the Vehicle 25sports_car = Vehicle(gas_engine) 26ev_truck = Vehicle(battery_motor) 27 28print("--- Sports Car ---") 29sports_car.drive() 30 31print("\n--- EV Truck ---") 32ev_truck.drive()