Go 设计模式--适配器模式

适配器:就是一个类的实例通过适配器功能可以实现一个它没有的功能

package adapt

import(
	"fmt"
)

type ChargeHeadB struct{//B的充电头

}

func (this *ChargeHeadB)ChargeB(){
	fmt.Println("Head B ready to charge...")
}

type ChargeIfC struct{//C的接口适配器
	TypeB //适配B
}

type TypeB interface{
	ChargeB()
}

func NewHead()TypeB{
	return &ChargeHeadB{}
}

func (this *ChargeIfC)ChargeB(){ //C的适配器调整到适合C的去充电
	this.ChargeC()
}

func (this *ChargeIfC)ChargeC(){
	fmt.Println("TypeC is charging...")
}

func AdaptBtoC(b TypeB)TypeB{
	return &ChargeIfC{
		TypeB : b,
	}
}

  

	b := adapt.NewHead()//创建新的充电头B
	c := adapt.AdaptBtoC(b)
	c.ChargeB()

  

猜你喜欢

转载自www.cnblogs.com/flycc/p/12629098.html
今日推荐