1
0
Fork 0
design-patterns/python/adapter/main.py

64 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
实例
汤宝宝有一个苹果手机手机原配lightning接口为了连接Type-C接口的充电器他需要一个转换器适配器来实现这个功能。
"""
from abc import ABC, abstractmethod
# 充电器类
class Charger:
def connect(self, type_c: "TypeCInterface"):
type_c.type_c_charging()
print("手机开始充电!\n")
# Type-C充电接口的接口
class TypeCInterface(ABC):
@abstractmethod
def type_c_charging(self):
pass
# 具体实现类
class TypeC(TypeCInterface):
def type_c_charging(self):
print("Type-C接口连接中...")
class Lightning:
def lightning_charging(self):
print("Lightning接口连接中...")
# 适配器类
class LightningToTypeCAdapter(TypeCInterface):
def __init__(self, lightning: Lightning):
self.lightning = lightning
def type_c_charging(self):
print("Type-C适配器转换中...")
self.lightning.lightning_charging()
def main():
print("============= 适配器模式 =============")
charger = Charger()
print("使用Type-C充电器给小米手机充电")
typec = TypeC()
charger.connect(typec)
print("使用Lightning接口转换器给苹果手机充电")
lightning = Lightning()
adapter = LightningToTypeCAdapter(lightning)
charger.connect(adapter)
print("=========== 适配器模式结束 ===========")
if __name__ == "__main__":
main()