【设计模式】第8节:结构型模式之“适配器模式”

一、简介

适配器模式是用来做适配的,它将不兼容的接口转换为可兼容的接口,让原本由于接口不兼容而不能一起工作的类可以一起工作。

适配器模式角色:

  • 请求者client:调用服务的角色
  • 目标Target:定义了Client要使用的功能
  • 转换对象Adaptee:需要被适配器转换的对象
  • 适配器Adapter:实现转换功能的对象

二、分类

有类适配器和对象适配器两种,前者用继承实现,后者用组合实现。

1. 类适配器

适配器的作用是将Adaptee中的方法都转为Target接口中的方法,而适配器类Adapter继承Adaptee,实现Target接口。

go 复制代码
type target interface{} {
  func1()
  func2()
}

type Adaptee struct {
}

func (*Adaptee) fa() {  
}

func (*Adaptee) fb() {  
}

type Adapter struct {
  Adaptee
}

func (*Adapter) func1() {
  fa()
}

2. 对象适配器

跟类适配器类似,唯一的不同在于适配器Adapter对于Adaptee是组合关系,而不是继承。

go 复制代码
type target interface{} {
  func1()
  func2()
}

type Adaptee struct {
}

func (*Adaptee) fa() {  
}

func (*Adaptee) fb() {  
}

type Adapter struct {
  adptee Adaptee
}

func (*Adapter) func1() {
  adptee.fa()
}

func (*Adapter) func2() {
  adptee.fb()
}

三、使用场景

1. 类适配器和对象适配器的选择

类适配器和对象适配器选用哪个,主要看Adaptee的接口个数,以及Adaptee和Target的契合程度。

  • 如果Adaptee的接口不多,选哪个都可以;
  • 如果Adaptee的接口很多
    • 如果Adaptee和Target的接口定义大多相同,则推荐使用类适配器,减少开发量。
    • 如果Adaptee和Target的接口定义大多不同,则推荐使用对象适配器,代码可以更灵活。

2. 适用场景

  1. 封装有缺陷的接口设计
  2. 统一多个类的接口设计
  3. 替换依赖的外部系统
  4. 兼容老版本接口
  5. 适配不同格式的数据
相关推荐
jump_jump7 小时前
GetX — Flutter 的瑞士军刀,还是过度封装的陷阱?
flutter·设计模式·前端框架
wuyikeer13 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
Old Uncle Tom17 小时前
Agent 技能的五种设计模式
设计模式
祁_z18 小时前
【ReACT 设计模式】(思考 - 行动 - 观察)
设计模式
Makoto_Kimur19 小时前
Spring用了哪些设计模式?
java·spring·设计模式
sg_knight20 小时前
设计模式实战:中介者模式(Mediator)
microsoft·设计模式·中介者模式
geovindu20 小时前
go: Prototype Pattern
开发语言·设计模式·golang·原型模式
我爱cope20 小时前
【从0开始学设计模式-11| 外观模式】
microsoft·设计模式·外观模式
两年半的个人练习生^_^21 小时前
每日一学:设计模式之代理模式
java·设计模式·代理模式
无籽西瓜a21 小时前
【西瓜带你学设计模式 | 第十九期 - 状态模式】状态模式 —— 状态流转与行为切换实现、优缺点与适用场景
java·后端·设计模式·状态模式·软件工程