[设计模式 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)
    }
}
相关推荐
GodKeyNet6 小时前
设计模式-模板模式
设计模式·模板模式
缘来是庄10 小时前
设计模式之建造者模式
java·设计模式·建造者模式
cui_win11 小时前
【基础】Golang语言开发环境搭建(Linux主机)
linux·golang·运维开发
铛铛啦啦啦13 小时前
“对象创建”模式之原型模式
设计模式·原型模式
牛奶咖啡1313 小时前
学习设计模式《十六》——策略模式
学习·设计模式·策略模式·认识策略模式·策略模式的优缺点·何时选用策略模式·策略模式的使用示例
叹一曲当时只道是寻常14 小时前
Softhub软件下载站实战开发(十):实现图片视频上传下载接口
golang·go·音视频
OpenC++14 小时前
【C++】观察者模式
c++·观察者模式·设计模式
一块plus15 小时前
2025 年值得一玩的最佳 Web3 游戏
算法·设计模式·程序员
缘来是庄16 小时前
设计模式之代理模式
java·设计模式·代理模式
勤奋的知更鸟17 小时前
Java 编程之策略模式详解
java·设计模式·策略模式