• go 适配器模式


    适配器模式用于转换一种接口适配另一种接口。

    实际使用中Adaptee一般为接口,并且使用工厂函数生成实例。

    在Adapter中匿名组合Adaptee接口,所以Adapter类也拥有SpecificRequest实例方法,又因为Go语言中非入侵式接口特征,其实Adapter也适配Adaptee接口。

    package adapter
    
    //Target 是适配的目标接口
    type Target interface {
    	Request() string
    }
    
    //Adaptee 是被适配的目标接口
    type Adaptee interface {
    	SpecificRequest() string
    }
    
    //NewAdaptee 是被适配接口的工厂函数
    func NewAdaptee() Adaptee {
    	return &adapteeImpl{}
    }
    
    //AdapteeImpl 是被适配的目标类
    type adapteeImpl struct {
    }
    
    //SpecificRequest 是目标类的一个方法
    func (*adapteeImpl) SpecificRequest() string {
    	return "adaptee method"
    }
    
    //NewAdapter 是Adapter的工厂函数
    func NewAdapter(adaptee Adaptee) Target {
    	return &adapter{
    		Adaptee: adaptee,
    	}
    }
    
    //Adapter 是转换Adaptee为Target接口的适配器
    type adapter struct {
    	Adaptee
    }
    
    //Request 实现Target接口
    func (a *adapter) Request() string {
    	return a.SpecificRequest()
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    测试方法

    package adapter
    
    import "testing"
    
    var expect = "adaptee method"
    
    func TestAdapter(t *testing.T) {
    	adaptee := NewAdaptee()
    	target := NewAdapter(adaptee)
    	res := target.Request()
    	if res != expect {
    		t.Fatalf("expect: %s, actual: %s", expect, res)
    	}
    }
    
    = expect {
    		t.Fatalf("expect: %s, actual: %s", expect, res)
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
  • 相关阅读:
    PhpStorm
    02 stm32-hal库 timer 基本定时器设定
    6、程序、进程、线程(二)
    Spring容器&Bean生命周期常见接口
    Angr-CTF学习笔记1-5
    ffmpeg之去除视频水印
    【Linux】文件权限、目录权限、掩码、粘滞位以及相关指令
    Spring事务的嵌套的详细理解,以及事务失效的场景解惑
    基于nodejs的电影交流网站-计算机毕业设计
    计算机网络第4章-IPv4
  • 原文地址:https://blog.csdn.net/lisus2007/article/details/134467993