設計模式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)
}

總結

適配器模式即將一種結構體類型(或接口)轉換爲另外一種結構體類型(或接口)。

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