# -*- coding: utf-8 -*-
# 假定有一个类Computer依赖于类Cpu
class Cpu:
def __init__(self,brand):
self.brand = brand
def __str__(self):
return f"CPU: <{self.brand}>"
class Computer:
def __init__(self):
self.cpu = Cpu('Intel')
def run(self):
print(f"running computer using {self.cpu}")
Computer().run()
# 当CPU类的构造方法发生调整的时候,
class CpuNew:
def __init__(self,brand,price):
self.brand = brand
self.price = price
def __str__(self):
return f"CPU: <{self.brand}:({self.price})>"
# 就得同时修改Computer类
class Computer:
def __init__(self):
self.cpu = CpuNew('Intel',2000)
def run(self):
print(f"running computer using {self.cpu}")
Computer().run()
# 把依赖的类的内部逻辑进行隐藏(Cpu的方法对Computer不可见),只保留Cpu通用的方法和属性
class Computer:
def __init__(self,cpu):
self.cpu = cpu
def run(self):
print(f"running computer using {self.cpu}")
Computer(CpuNew('Intel',2000)).run()
# 这就是一种依赖注入
依赖注入
最新推荐文章于 2024-09-24 11:33:58 发布