美文网首页
适配器模式

适配器模式

作者: 耗子_aca3 | 来源:发表于2020-05-11 15:13 被阅读0次
  • 概念:适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
    意图:将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
  • demo:
package pattern

import (
    "fmt"
    "testing"
)

func TestAdapter(t *testing.T) {
    var play Play = AdapterCreator("gameSound", "xxxxxx", "lalalala")
    play.PlayMusic()

    play = AdapterCreator("music", "yyyyyyyyyy")
    play.PlayMusic()
}

type Play interface {
    PlayMusic()
}

// 第一个struct,直接实现PlayMusic方法
type MusicPlayer struct {
    Src string
}

func (m * MusicPlayer) PlayMusic()  {
    fmt.Printf("play a music, src is: %s\n", m.Src)
}

// 第二个struct,转一手先
type GameSound struct {
    Url string
    SoundName string
}

func (g *GameSound) PlaySound()  {
    fmt.Printf("play a game sound, url is: %s, sound name is: %s\n", g.Url, g.SoundName)
}

// adapter
type GameSoundAdapter struct {
    GameSound GameSound
}

func (g GameSoundAdapter) PlayMusic()  {
    g.GameSound.PlaySound()
}
// adapter

func AdapterCreator(adapterType string, data ...string) Play {

    switch adapterType {
        case "music":
            var musicPlayer Play = &MusicPlayer{Src: data[0]}
            return musicPlayer
        case "gameSound":
            var gameSound GameSound = GameSound{Url: data[0], SoundName: data[1]}
            var gameSoundAdapter Play = &GameSoundAdapter{GameSound: gameSound}
            return gameSoundAdapter
        default:
            return nil
    }
}

相关文章

  • Java设计模式(二)

    talk is cheap show me the code 适配器模式 类适配器模式 接口适配器模式 对象适配器...

  • 适配器模式

    目录 1、什么是适配器模式? 2、适配器模式结构? 3、如何实现适配器模式? 4、适配器模式的特点? 5、适配器模...

  • 设计模式之适配器模式

    适配器模式: 类适配器模式、对象适配器模式、接口适配器模式 1.类适配器模式:新的接口出现了,但是和老的接口不兼容...

  • 学习iOS设计模式第一章 适配器(Adapter)

    今天学习了iOS设计模式中的适配器模式,适配器有两种模式对象适配器模式-- 在这种适配器模式中,适配器容纳一个它包...

  • 第4章 结构型模式-适配器模式

    一、适配器模式简介 二、适配器模式的优点 三、适配器模式的实例

  • 设计模式(Design Patterns)适配器模式(Adapt

    适配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。 类的适配器模式 场景:将一个类转换成...

  • 适配器模式

    适配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。适配器模式将某个类的接口转换成客户端期...

  • 适配器模式

    先直观感受下什么叫适配器 适配器模式有类的适配器模式和对象的适配器模式两种不同的形式。 类适配器模式 对象适配器模...

  • 适配器模式

    适配器模式 一、适配器模式定义 适配器模式的定义是,Convert the interface of a clas...

  • 设计模式:结构型

    享元模式 (Pools,Message) 代理模式 适配器模式 :类适配器和对象适配器 装饰者模式 外观模式 桥接...

网友评论

      本文标题:适配器模式

      本文链接:https://www.haomeiwen.com/subject/pfmunhtx.html