做網(wǎng)站公司哪個(gè)品牌好免費(fèi)推廣的方式有哪些
目錄
適配器模式(Adapter Pattern)
優(yōu)缺點(diǎn)
使用場(chǎng)景
注意事項(xiàng)
代碼實(shí)現(xiàn)
適配器模式(Adapter Pattern)
?????適配器模式(Adapter Pattern)是作為兩個(gè)不兼容的接口之間的橋梁。將一個(gè)類的接口轉(zhuǎn)化為客戶希望的另外一個(gè)接口。適配器模式使得原本由于接口不兼容而不能一起工作的那些類可以一起工作。
優(yōu)缺點(diǎn)
(1)優(yōu)點(diǎn):
- 可以讓任何兩個(gè)沒(méi)有關(guān)聯(lián)的類一起運(yùn)行。
- 提高了類的復(fù)用。
- 增加了類的透明度。
- 靈活性好。
(2)缺點(diǎn):過(guò)多地使用適配器,會(huì)讓系統(tǒng)非常零亂,不易整體進(jìn)行把握。比如,明明看到調(diào)用的是 A 接口,其實(shí)內(nèi)部被適配成了 B 接口的實(shí)現(xiàn),一個(gè)系統(tǒng)如果太多出現(xiàn)這種情況,無(wú)異于一場(chǎng)災(zāi)難。因此如果不是很有必要,可以不使用適配器,而是直接對(duì)系統(tǒng)進(jìn)行重構(gòu)。
使用場(chǎng)景
- 有動(dòng)機(jī)地修改一個(gè)正常運(yùn)行的系統(tǒng)的接口,這時(shí)應(yīng)該考慮使用適配器模式。
注意事項(xiàng)
??????適配器不是在詳細(xì)設(shè)計(jì)時(shí)添加的,而是解決正在服役的項(xiàng)目的問(wèn)題。
代碼實(shí)現(xiàn)
package mainimport "fmt"// 新接口
type MusicPlayer interface {play(fileType string, fileName string)
}// 舊接口
type ExistPlayer struct {
}func (e *ExistPlayer) PlayMp3(filName string) {fmt.Println("play mp3:", filName)
}
func (e *ExistPlayer) PlayWma(fileName string) {fmt.Println("play wma:", fileName)
}// 適配器
type PlayerAdapter struct {existPlayer ExistPlayer
}func (p *PlayerAdapter) play(fileType string, fileName string) {switch fileType {case "mp3":p.existPlayer.PlayMp3(fileName)case "wma":p.existPlayer.PlayWma(fileName)default:fmt.Println("暫不支持此類型文件播放")}
}
func main() {player := PlayerAdapter{}player.play("mp3", "nsjd")player.play("wma", "孤勇者")
}