- Python 设计模式教程
- Python 设计模式 - 首页
- 介绍
- Python 设计模式 - 要点
- 模型-视图-控制器模式 (MVC)
- 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接口。
广告