设计模式golang-适配器模式

适配器模式

定义

将一个接口转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。

角色

1.源接口。

2.适配目的接口。

3.适配结构体。

例子

人类能说话,动物也能发声叫,人类能学动物叫,需要一个转换器把人类的叫声转换为动物的叫声。

//适配目的接口
type AnimalSound interface{
Sound()
}
//源结构体
type PeopleSpeak sturct{
  Speak string
}

func(s *PeopleSpeak)Speak(){
   fmt.Println(s.Speak)
}

type Dog struct{}
func(a *Dog)Sound(){
  fmt.Println("wang wang wang")
}

//转换器,把人类的叫声转换为动物的叫声
type PeopleSpeakAdapter struct{
	Speaker PeopleSpeak
}
fun (s *PeopleSpeakAdapter)Sound(){
	s.Speaker.Speak()
}

func Sound(as AnimalSound){
 as.Sound()
}

func main(){
    //将人叫声转换为动物叫声
	psa :=PeopleSpeakAdapter{Speaker:PeopleSpeak{Speak:"wang wang wang"}}
	Sound(psa)
}

总结

适配器模式即将一种结构体类型(或接口)转换为另外一种结构体类型(或接口)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章