5

go设计模式之适配器模式浅谈

 3 years ago
source link: https://studygolang.com/articles/35029
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

适配器模式

概念:适配器模式(Adapter Pattern)是作为两个不兼容的接口(结构体)之间的桥梁

什么时候用

举个例子,原先用Iphone6听音乐,使用的是3.5mm耳机,后来手机坏了,但耳机还在,于是买了一个Iphone12手机,
Iphone12使用的是Lightning接口,原先的旧耳机就不能直接使用了,这时我们可以买一个Lightning转3.5mm的转接头,
这里的转接头就相当于我们适配器

原先的Iphon6

//原先的Iphon6手机
type Iphone6 struct{}

//3.5mm标准接口听音乐
func (*Iphone6) standardPlayMusic() {
    fmt.Println("3.5mm标准接口 play music")
}
//Iphone6听音乐
i6 := new(Iphone6)
i6.standardPlayMusic() //i6通过3.5mm标准接口播放音乐

Iphone6手机坏了,买一个新的Iphoe12

//新的Iphone12
type Iphone12 struct{}

//Lightning接口听音乐
func (*Iphone12) LightningPlayMusic() {
    fmt.Println("Lightning play music")
}
//Iphone12听音乐
i12 := new(Iphone12)
i12.standardPlayMusic()   //i12没有3.5mm标准接口所有会报错
i12.LightningPlayMusic()  //i12只能通过Lightning接口播放音乐

买一个转接头,即构造一个适配器

//实现Iphone12可以使用3.5mm标准接口听音乐
type Adapter struct {
    *Iphone12         //通过新手机嵌入到适配器里
}
//给适配器添加一个3.5mm标准接口播放音乐的方法
func (a *Adapter) standardPlayMusic() {
    a.LightningPlayMusic()                             //通过调用Iphone12的Lightning接口播放音乐
    fmt.Println("Lightning转3.5mm标准接口 play music")  //通过转接口内部转换转换为3.5mm接口输出音乐
}

新Iphone12通过适配器使用3.5mm接口播放音乐

i12 = new(Iphone12)
adapter := Adapter{i12}
adapter.standardPlayMusic() //i12经过适配器由Lightning转3.5mm接口播放音乐

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK