- 概念:适配器模式(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
}
}
网友评论