golang适配器模式

108 阅读1分钟

适配器模式是一种结构性模式。如字面意思,它能使不兼容的对象能正常工作。

实现

以现实中充电器类型 lightning,type-c 两种手机充电插头为例。

定义 充电 的接口

package main

type IPower interface {
	linkPower()
}

具体实现

  • 假设一开始对接的是lightning接口
package main

type Applephone struct{}

func NewApplephone() *Applephone {
	return &Applephone{}
}

func (a *Applephone) linkPower() {
	fmt.Println("phone lightning link .....")
}


  • 因为业务增加了type-c 接口
package main

// type-c 业务接口
type MIphone struct{}

func (a *MIphone) linkPowerByTypeC() {
	fmt.Println("phone type-c link .....")
}

// 增加一个适配器
type MIphoneAdaptor struct {
	miAdaptor *MIphone
}

func NewMIphoneAdaptor() *MIphoneAdaptor {
	return &MIphoneAdaptor{
		miAdaptor: &MIphone{},
	}
}

func (a *MIphoneAdaptor) linkPower() {
	fmt.Println("mi phone converting lightning ....")
	a.miAdaptor.linkPowerByTypeC()
}

客户端调用

package main

type Client struct{}

func (c *Client) PhonePower(phone IPower) {
	fmt.Println("start phone power....")
	phone.linkPower()
}

func client() {
	c := &Client{}
	// 之前用的是apple 数据线
	phone := NewApplephone()
	c.PhonePower(phone)

	// 小米手机要充电,需要使用适配器才行
	MIphone := &MIphoneAdaptor{}
	c.PhonePower(MIphone)
}

总结

适配器模式以上举例中,适配器解决的问题是,兼容不同第三方的标准。开发过程中,经常有很多服务的接口返回格式不同,提供给客户端的接口需要一致,不知不觉就用了此中设计模式。此设计模式,并非一开始的一种设计,而是对设计好的不同方案的兼容和补救方式。