概念
适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
需求
利用适配器模式帮助姚明听懂教练的战术
UML图

代码
抽象球员接口
type Player interface {
Attack()
Defense()
}
具体球员类
type ForWards struct {
Name string
}
func (f *ForWards) Attack() {
fmt.Println("前锋:" + f.Name + "进攻")
}
func (f *ForWards) Defense() {
fmt.Println("前锋:" + f.Name + "防守")
}
type Center struct {
Name string
}
func (c *Center) Attack() {
fmt.Println("中锋:" + c.Name + "进攻")
}
func (c *Center) Defense() {
fmt.Println("中锋:" + c.Name + "防守")
}
type Gurads struct {
Name string
}
func (g *Gurads) Attack() {
fmt.Println("后卫:" + g.Name + "进攻")
}
func (g *Gurads) Defense() {
fmt.Println("后卫:" + g.Name + "防守")
}
外籍球员类
type Translator struct {
ForeignCenter ForeignCenter
}
func (t *Translator) Attack() {
t.ForeignCenter.进攻()
}
func (t *Translator) Defense() {
t.ForeignCenter.防守()
}
翻译员类
type ForeignCenter struct {
Name string
}
func (c *ForeignCenter) 进攻() {
fmt.Println("外籍中锋:" + c.Name + "进攻")
}
func (c *ForeignCenter) 防守() {
fmt.Println("外籍中锋:" + c.Name + "防守")
}
测试
//适配器模式
b := adapterPattern.ForWards{Name: "巴蒂尔"}
b.Attack()
m := adapterPattern.Gurads{Name: "麦格雷迪"}
m.Attack()
ym := adapterPattern.Translator{ForeignCenter: adapterPattern.ForeignCenter{Name: "姚明"}}
ym.Attack()
ym.Defense()
文章介绍了适配器模式的概念,通过编程示例展示了如何在Go语言中使用适配器模式,使原本接口不兼容的外籍球员(以姚明为代表)能够理解并执行教练的战术指令。适配器将外籍球员的接口转换为客户(教练)期望的形式。
1062

被折叠的 条评论
为什么被折叠?



