[设计模式 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)
    }
}
相关推荐
南猿北者1 天前
go环境搭建--Linux
linux·开发语言·golang
开心香辣派小星1 天前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Lovely Ruby1 天前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·学习·golang
互亿无线明明2 天前
如何为全球业务构建可扩展的“群发国际短信接口”?
java·c++·python·golang·eclipse·php·erlang
张较瘦_2 天前
[论文阅读] 软件工程 - 供应链 | 从Log4Shell到Go组件漏洞:一篇文看懂开源依赖安全的核心痛点与解决方案
论文阅读·golang·开源
wadesir2 天前
Go语言反射之结构体的深比较(详解reflect.DeepEqual在结构体比较中的应用)
开发语言·后端·golang
咨询QQ:4877392782 天前
一款基于.NET Core Web + Bootstrap的企业级快速后台开发框架。 内置模块如
适配器模式
阿杰同学2 天前
Java 设计模式 面试题及答案整理,最新面试题
java·开发语言·设计模式
xunyan62342 天前
面向对象(下)-模版方法的设计模式其应用场景
java·学习·设计模式
此剑之势丶愈斩愈烈2 天前
设计模式学习
学习·设计模式