[设计模式 Go实现] 结构型~适配器模式

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

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

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

adapter.go
go 复制代码
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()
}
adapter_test.go
go 复制代码
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)
    }
}
相关推荐
小屁猪qAq5 小时前
设计模式总纲
开发语言·c++·设计模式
小简GoGo6 小时前
前端常用设计模式快速入门
javascript·设计模式
CTO Plus技术服务中9 小时前
一栈式、系统性的C、C++、Go、网络安全、Linux运维开发笔记和面试笔记
c++·web安全·golang
modelmd9 小时前
Go、Java 的值类型和引用类型对比
java·golang
会员果汁9 小时前
17.设计模式-单例模式(Singleton)
单例模式·设计模式
资深web全栈开发10 小时前
高并发的本质:超越语言的协作哲学——以 Go HTTP 服务器为例
服务器·http·golang·系统设计·goroutine·高并发架构·go并发
派大鑫wink10 小时前
【Day37】MVC 设计模式:原理与手动实现简易 MVC 框架
java·设计模式·mvc
会员果汁10 小时前
18.设计模式-桥接模式
设计模式·桥接模式
老蒋每日coding10 小时前
AI Agent 设计模式系列(九)——学习和适应模式
人工智能·学习·设计模式
bing.shao10 小时前
Golang 在OPC领域的应用
开发语言·后端·golang