from abc import ABC, abstractmethod
# Adaptee
class Power110V:
def output(self):
return 110
# Adaptee
class Power20V:
def output(self):
return 20
# Adaptee
class Power5V:
def output(self):
return 20
# Target
class PowerStandard(ABC):
@abstractmethod
def output220V(self):
pass
# Adapter
class PowerAdapter(PowerStandard):
def __init__(self, power):
self.power = power
def output220V(self):
if isinstance(self.power, Power110V):
return self.power.output() * 2
elif isinstance(self.power, Power20V):
return self.power.output() * 11
else:
raise Exception('%sv is not supported yet'%self.power.output())
if __name__ == '__main__':
# 110V 转换为 220V
adapter = PowerAdapter(Power110V())
print(adapter.output220V())
# 10V 转换为 220V
adapter = PowerAdapter(Power20V())
print(adapter.output220V())
# 还不支持 20V 转换为 220V
adapter = PowerAdapter(Power5V())
print(adapter.output220V())
【设计模式】适配器模式
最新推荐文章于 2024-10-11 19:57:51 发布