chiachan
chiachan
Published on 2020-08-17 / 680 Visits
0

Adapter模式(适配器模式)

什么是适配器模式?

  • 桥接模式即用于填补现有程序和所需程序之间差异的设计模式
  • 作用是加个适配器以便于复用
  • 适配器会对现有的类进行适配,生产新的类
  • 适配器模式可以在完全不改变现有代码的前提下使现有代码适配于新的接口
  • 适配器模式可以是新旧版本兼容,帮助我们轻松地同时维护新版本和旧版本
  • 适配器模式用于填补具有不同接口的两个类之间的缝隙

示范代码(adapter.go)

  • Adaptee是现有的类
  • Adapter是所需的类(即适配器)
  • Adapter是将Adaptee的功能在新需求下的体现
package Adapter

import "fmt"

type Target interface {
	targetMethod1()
	targetMethod2()
}

type Adaptee struct {
}

func (a *Adaptee) methodA() {
	fmt.Println("methodA")
}

func (a *Adaptee) methodB() {
	fmt.Println("methodB")
}

type Adapter struct {
	Target
	*Adaptee
}

func (a *Adapter) targetMethod1() {
	a.methodA()
}

func (a *Adapter) targetMethod2() {
	a.methodB()
}

测试用例(adapter_test.go)

package Adapter

import "testing"

func TestAdapterMethodA(t *testing.T) {
	adapter := Adapter{}
	adapter.methodA()
	adapter.methodB()
}