golang实现设计模式之适配器模式-优缺点,适用场景

发布时间 2023-06-09 18:22:40作者: 进击的davis

适配器模式是一种结构型设计模式,它是通过接口转换,使得原先接口不被兼容的其他类可以一起工作。

类型

  • 类结构型

特点:
- 程序耦合性高
- 要求程序员对组件内部结构熟悉
- 应用相对少些
类适配器模式可以用过继承的方式来实现。

  • 对象结构型

特点:可重用性较差。

对象适配器允许一个adapter和多个adaptee,即多个adaptee及其子类一起工作,可釆用将现有组件库中已经实现的组件引入适配器类中,该类同时实现当前系统的业务接口。

结构

  • 1.目标(Target)接口。当前系统业务所期待的接口,它可以是抽象类或接口。
  • 2.适配者(Adaptee)类。它是被访问和适配的现存组件库中的组件接口。
  • 3.适配器(Adapter)类。它是一个转换器,通过继承或引用适配者的对象,把适配者接口转换成目标接口,让客户按目标接口的格式访问适配者。

优缺点

  • 优点

1.客户端通过适配器可以透明地调用目标接口。
2.复用了现存的类,程序员不需要修改原有代码而重用现有的适配者类。
3.将目标类和适配者类解耦,解决了目标类和适配者类接口不一致的问题。
4.在很多业务场景中符合开闭原则。

  • 缺点

1.适配器编写过程需要结合业务场景全面考虑,可能会增加系统的复杂性。
2.增加代码阅读难度,降低代码可读性,过多使用适配器会使系统代码变得凌乱。

适用场景

  • 1.以前开发的系统存在满足新系统功能需求的类,但其接口同新系统的接口不一致。
  • 2.使用第三方提供的组件,但组件接口定义和自己要求的接口定义不同。

代码实现

package main

import "fmt"

/*
业务场景描述:
- 通过Lightning接口连接电脑,mac实现Lightning接口,但win的电脑实现的是USB接口,此时需要通过一个适配器,lightning -> USB
- 更过,如果是type-c的接口呢,增加一个适配
 */

// 1.target interface, declare computer interface
type computer interface {
   InsertIntoLightningPort()
}

// 2.implement target struct
type mac struct {

}

func (m *mac) InsertIntoLightningPort()  {
   fmt.Println("Lightning connector is plugged into mac machine.")
}

// 3.adpatee
type windows struct {

}

func (w *windows) InsertIntoUSBPort()  {
   fmt.Println("USB connector is plugged into windows machine.")
}

// 4.adapter
type winAdapter struct {
   winMachine *windows
}

func (w *winAdapter) InsertIntoLightningPort()  {
   fmt.Println("Adapter converts Lightning signal to USB.")
   w.winMachine.InsertIntoUSBPort()
}

// 5.client
type client struct {

}

func (c *client) insertLightningConnectorIntoComputer(com computer)  {
   fmt.Println("Client inserts Lightning connector into computer.")
   com.InsertIntoLightningPort()
}

func main()  {
   c := &client{}
   m := &mac{}
   // mac直接用
   c.insertLightningConnectorIntoComputer(m)

   winm := &windows{}
   winA := &winAdapter{winMachine: winm}
   // windows加一个适配器也可以用
   c.insertLightningConnectorIntoComputer(winA)
   /*
   Client inserts Lightning connector into computer.
   Lightning connector is plugged into mac machine.
   Client inserts Lightning connector into computer.
   Adapter converts Lightning signal to USB.
   USB connector is plugged into windows machine.
    */
}

参考文章: