当前位置: 首页 > article >正文

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

目录

适配器模式(Adapter Pattern)

优缺点

使用场景

注意事项

代码实现


适配器模式(Adapter Pattern)

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

优缺点

(1)优点:

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

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

使用场景

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

注意事项

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

代码实现

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", "孤勇者")
}

http://www.kler.cn/news/162973.html

相关文章:

  • SAP UI5 walkthrough step7 JSON Model
  • 伦茨科技宣布ST17H6x芯片已通过Apple Find My「查找」认证
  • HTML5 Audio/Video 标签、属性、方法、事件汇总(详细)
  • 目标检测器技术演进简史
  • 3D点云:平面模型上提取凸(凹)多边形方法
  • jenkins中“Jenkins Plot Plugin”的使用方法,比较两个excel的数据差异
  • LeetCode124.二叉树中最大路径和
  • 微信小程序 - 格式化操作 moment.js格式化常用使用方法总结大全
  • 代理IP怎么使用?Mac苹果系统设置http代理IP教程
  • react-photo-view 的介绍、安装、使用。
  • HarmonyOS鸿蒙操作系统架构开发
  • Gitleaks - 一款高效的Github仓库敏感信息泄露查询工具
  • 小程序自动更新功能
  • RHEL网络服务器
  • 云计算ACP认证考试题库0-100
  • harmonyOS开发技巧(二)——沉浸式以及状态栏高
  • 前端知识笔记(三十七)———Django与Ajax
  • 2023年12月8日:UI登陆界面
  • 用C语言实现队列的顺序结构
  • 4.PyTorch——优化器
  • Bert-vits2新版本V2.1英文模型本地训练以及中英文混合推理(mix)
  • 【c语言指针详解】指针的基本概念和用法
  • 面对对象基础案例
  • React中使用react-json-view展示JSON数据
  • 2023年甘肃职业院校技能大赛(中职教师组)网络安全竞赛样题(五)
  • 持续集成交付CICD:CentOS 7 安装 Nexus 3.63
  • Flask template+Vue +项目中include引入其他模版(其他模版也会用到vue)的使用探索
  • 独立服务器的主要应用方向有什么_Maizyun
  • 云原生(Cloud Native)——概念,技术,背景,优缺点,实践例子
  • Vue3如何优雅的跨组件通信