- Python 设计模式教程
- Python 设计模式 - 主页
- 介绍
- Python 设计模式 - 要点
- 模型视图控制器模式
- Python 设计模式 - 单例
- Python 设计模式 - 工厂
- Python 设计模式 - 构建器
- Python 设计模式 - 原型
- Python 设计模式 - 外观
- Python 设计模式 - 命令
- Python 设计模式 - 适配器
- Python 设计模式 - 装饰器
- Python 设计模式 - 代理
- 责任链模式
- Python 设计模式 - 观察者
- Python 设计模式 - 状态
- Python 设计模式 - 策略
- Python 设计模式 - 模板
- Python 设计模式 - 享元
- 抽象工厂
- 面向对象
- 面向对象的概念实现
- Python 设计模式 - 迭代器
- 词典
- 列表数据结构
- Python 设计模式 - 集
- Python 设计模式 - 队列
- 字符串和序列化
- Python 中的并发
- Python 设计模式 - 反
- 异常处理
- Python 设计模式资源
- 快速指南
- Python 设计模式 - 资源
- 讨论
Python 设计模式 - 适配器
适配器模式充当两个不兼容接口之间的桥梁。这种类型的设计模式属于结构模式,因为这种模式结合了两个独立接口的功能。
此模式涉及单个类,该类负责连接独立或不兼容接口的功能。现实生活中的一个例子就是读卡器,它充当存储卡和笔记本电脑之间的适配器。将存储卡插入读卡器,再将读卡器插入笔记本电脑,这样笔记本电脑就可以读取存储卡了。
适配器设计模式有助于类一起工作。它根据需要将一个类的接口转换为另一个接口。该模式包括命名一个名称和多种形式的物种形成和多态性。比如说可以根据收集的要求使用的形状类。
有两种类型的适配器模式 -
对象适配器模式
这种设计模式依赖于对象实现。因此,它被称为对象适配器模式。
类适配器模式
这是实现适配器设计模式的另一种方法。该模式可以使用多重继承来实现。
如何实现适配器模式?
现在让我们看看如何实现适配器模式。
class EuropeanSocketInterface:
def voltage(self): pass
def live(self): pass
def neutral(self): pass
def earth(self): pass
# Adaptee
class Socket(EuropeanSocketInterface):
def voltage(self):
return 230
def live(self):
return 1
def neutral(self):
return -1
def earth(self):
return 0
# Target interface
class USASocketInterface:
def voltage(self): pass
def live(self): pass
def neutral(self): pass
# The Adapter
class Adapter(USASocketInterface):
__socket = None
def __init__(self, socket):
self.__socket = socket
def voltage(self):
return 110
def live(self):
return self.__socket.live()
def neutral(self):
return self.__socket.neutral()
# Client
class ElectricKettle:
__power = None
def __init__(self, power):
self.__power = power
def boil(self):
if self.__power.voltage() > 110:
print "Kettle on fire!"
else:
if self.__power.live() == 1 and \
self.__power.neutral() == -1:
print "Coffee time!"
else:
print "No power."
def main():
# Plug in
socket = Socket()
adapter = Adapter(socket)
kettle = ElectricKettle(adapter)
# Make coffee
kettle.boil()
return 0
if __name__ == "__main__":
main()
输出
上述程序生成以下输出 -
解释
该代码包括具有各种参数和属性的适配器接口。它包括 Adaptee 以及实现所有属性并将输出显示为可见的 Target 接口。