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", "孤勇者")
}
相关推荐
秦苒&13 分钟前
【C语言指针二】从入门到通透:核心知识点全梳理(野指针,assert断言,指针的使用和传址调用,数组名的理解和使用指针反访问数组)
c语言·开发语言
qq_479875431 小时前
C++ 网络编程中的 Protobuf 消息分发 (Dispatcher) 设计模式
网络·c++·设计模式
Y1rong4 小时前
C++ QT之记事本
开发语言·qt
ZouZou老师7 小时前
C++设计模式之装饰器模式:以家具生产为例
c++·设计模式·装饰器模式
ZouZou老师8 小时前
C++设计模式之桥接模式:以家具生产为例
c++·设计模式·桥接模式
diegoXie8 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条8 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle8 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
韩立学长8 小时前
基于Springboot流浪动物领养网站0kh2iyb4(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
ZouZou老师8 小时前
C++设计模式之组合模式:以家具生产为例
c++·设计模式·组合模式