GO设计模式——7、适配器模式(结构型)

目录

[适配器模式(Adapter Pattern)](#适配器模式(Adapter Pattern))

优缺点

使用场景

注意事项

代码实现


适配器模式(Adapter Pattern)

适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。将一个类的接口转化为客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

优缺点

(1)优点:

  • 可以让任何两个没有关联的类一起运行。
  • 提高了类的复用。
  • 增加了类的透明度。
  • 灵活性好。

(2)缺点:过多地使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是 A 接口,其实内部被适配成了 B 接口的实现,一个系统如果太多出现这种情况,无异于一场灾难。因此如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。

使用场景

  • 有动机地修改一个正常运行的系统的接口,这时应该考虑使用适配器模式。

注意事项

适配器不是在详细设计时添加的,而是解决正在服役的项目的问题。

代码实现

Go 复制代码
package main

import "fmt"

// 新接口
type MusicPlayer interface {
    play(fileType string, fileName string)
}

// 旧接口
type ExistPlayer struct {
}

func (e *ExistPlayer) PlayMp3(filName string) {
    fmt.Println("play mp3:", filName)
}
func (e *ExistPlayer) PlayWma(fileName string) {
    fmt.Println("play wma:", fileName)
}

// 适配器
type PlayerAdapter struct {
    existPlayer ExistPlayer
}

func (p *PlayerAdapter) play(fileType string, fileName string) {
    switch fileType {
    case "mp3":
       p.existPlayer.PlayMp3(fileName)
    case "wma":
       p.existPlayer.PlayWma(fileName)
    default:
       fmt.Println("暂不支持此类型文件播放")
    }
}
func main() {
    player := PlayerAdapter{}
    player.play("mp3", "nsjd")
    player.play("wma", "孤勇者")
}
相关推荐
kyriewen111 分钟前
WebAssembly:前端界的“外挂”,让C++代码在浏览器里跑起来
开发语言·前端·javascript·c++·单元测试·ecmascript
舒一笑9 分钟前
用几十行代码搞定 Chat 接口透明转发:跨环境轻量级网关实战
后端·程序员·架构
铁皮饭盒1 小时前
成为AI全栈 - 第3课:路由 RESTful Elysia 状态码 设计规范
前端·后端·全栈
我叫黑大帅2 小时前
如何通过 Python 实现招聘平台自动投递
后端·python·面试
狼爷2 小时前
短视频播放量(Views)计数系统实现方案:高并发、不丢数的工业级实践
后端·架构
其实防守也摸鱼2 小时前
CTF密码学综合教学指南--第九章
开发语言·网络·python·安全·网络安全·密码学·ctf
砚底藏山河2 小时前
Python量化开发:2026最佳实时股票数据API接口推荐与对比
开发语言·windows·python
AlunYegeer3 小时前
JAVA,以后端的视角理解前端。在全栈的路上迈出第一步。
java·开发语言·前端
苍何3 小时前
我用 Tabbit 浏览器搭了一套内容创作全自动流水线,太香了!
后端
苍何3 小时前
全网首测,TRAE SOLO 的 AI 麦克风!
后端