当前位置:网站首页>Design pattern adapter pattern (go language)

Design pattern adapter pattern (go language)

2020-12-06 21:08:30 Cucumber and potato

1. Adapter pattern

Generally speaking, adapter mode is to connect two incompatible interfaces , It's like a bridge

2. Example

 

package adaptor

import "fmt"



//  Good libraries are available online   Music playing 
// (  Old interface )
type ExistPlayerAdaptee struct {
}

func (*ExistPlayerAdaptee) playMp3(fileName string) {
	fmt.Println("play mp3 :", fileName)
}
func (*ExistPlayerAdaptee) playWma(fileName string) {
	fmt.Println("play wma :", fileName)
}



//  Our interface ( The new interface )—— Music playing 
type MusicPlayerTarget interface {
	play(fileType string, fileName string)
}
//  Adapter 
type PlayerAdaptor struct {
	//  Holding an old interface 
	existPlayer ExistPlayerAdaptee
}

//  Implement new interfaces 
func (player *PlayerAdaptor) play(fileType string, fileName string) {
	switch fileType {
	case "mp3":
		player.existPlayer.playMp3(fileName)
	case "wma":
		player.existPlayer.playWma(fileName)
	default:
		fmt.Println(" This type of file playback is not supported at the moment ")
	}
}
package adaptor

import "testing"

func TestAdaptor(t *testing.T) {
	player := PlayerAdaptor{}
	player.play("mp3", " test ")
	player.play("wma", " My motherland ")
	player.play("mp4", " Decade ")
}

 

版权声明
本文为[Cucumber and potato]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201206210513993y.html