Python设计模式——适配器模式

(一)适配器模式

适配器模式:
将一个类的接口转换成客户希望的另一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。适配器模式主要用于 帮助我们实现两个不兼容接口之间的兼容。

两种实现方式:

  • 类适配器:使用多继承 。多个类组合而成的系统。

  • 对象适配器:使用组合。在一个类中定义另外一个类的实例,通过类与对象的组合形成更大的系统,可以通过类中的对象属性去调用这个对象的方法。

适配器模式中的角色:

  • 目标接口(Target)
  • 待适配的类(Adaptee)
  • 适配器(Adapter)

适配器模式使用场景:

  • 想使用一个已经存在的类,而它的接口不符合你的要求
  • 想使用一些已经存在的子类,但不可能对每一个都进行子类化以匹配它们的接口,对象适配器可以适配它的父类接口

python代码实现实例:

# (一)类适配器
# 步骤:
# 1.创建一个新的类
# 2.继承需要进行转换的类
# 3.在新的类中实现旧系统的接口
class ExecuteCmd:
    def __init__(self, cmd):
        self.cmd = cmd

    def cmd_exe(self):
        print(f"使用cmd_exe执行{
      
      self.cmd}命令")


class NewExecuteCmd:
    def __init__(self, cmd):
        self.cmd = cmd

    def run_cmd(self):
        print(f"使用run_cmd执行{
      
      self.cmd}命令")


class ExecuteAdapter(NewExecuteCmd):
    """继承新系统的类"""

    def cmd_exe(self):
        """直接在适配器中实现旧系统的接口"""
        return self.run_cmd()


# 旧接口
old_obj = ExecuteCmd("ls")
old_obj.cmd_exe()

# 新接口需要进行适配
new_obj = ExecuteAdapter("ls")
new_obj.cmd_exe()

输出:
=======
使用cmd_exe执行ls命令
使用run_cmd执行ls命令

python代码实现实例:

# (二)类适配器
# 步骤:
# 1.创建一个新的类
# 2.初始化传入需要适配的对象
# 3.接口调用初始化中的对象的老方法
class ExecuteCmd:
    def __init__(self, cmd):
        self.cmd = cmd

    def cmd_exe(self):
        print(f"使用cmd_exe执行{
      
      self.cmd}命令")


class NewExecuteCmd:
    def __init__(self, cmd):
        self.cmd = cmd

    def run_cmd(self):
        print(f"使用run_cmd执行{
      
      self.cmd}命令")


class ExecuteAdapter():
    def __init__(self, new_exec_obj):
        self.exec_obj = new_exec_obj

    def cmd_exe(self):
        """直接在适配器中实现旧系统的接口"""
        return self.exec_obj.run_cmd()


# 旧接口
old_obj = ExecuteCmd("ls")
old_obj.cmd_exe()

# 新接口需要进行适配
new_obj = ExecuteAdapter(NewExecuteCmd("ls"))
new_obj.cmd_exe()

Guess you like

Origin blog.csdn.net/weixin_45455015/article/details/127557479