[设计模式 Go实现] 结构型~外观模式

API 为facade 模块的外观接口,大部分代码使用此接口简化对facade类的访问。

facade模块同时暴露了a和b 两个Module 的NewXXX和interface,其它代码如果需要使用细节功能时可以直接调用。

facade.go
go 复制代码
package facade

import "fmt"

func NewAPI() API {
    return &apiImpl{
        a: NewAModuleAPI(),
        b: NewBModuleAPI(),
    }
}

//API is facade interface of facade package
type API interface {
    Test() string
}

//facade implement
type apiImpl struct {
    a AModuleAPI
    b BModuleAPI
}

func (a *apiImpl) Test() string {
    aRet := a.a.TestA()
    bRet := a.b.TestB()
    return fmt.Sprintf("%s\n%s", aRet, bRet)
}

//NewAModuleAPI return new AModuleAPI
func NewAModuleAPI() AModuleAPI {
    return &aModuleImpl{}
}

//AModuleAPI ...
type AModuleAPI interface {
    TestA() string
}

type aModuleImpl struct{}

func (*aModuleImpl) TestA() string {
    return "A module running"
}

//NewBModuleAPI return new BModuleAPI
func NewBModuleAPI() BModuleAPI {
    return &bModuleImpl{}
}

//BModuleAPI ...
type BModuleAPI interface {
    TestB() string
}

type bModuleImpl struct{}

func (*bModuleImpl) TestB() string {
    return "B module running"
}
facade_test.go
go 复制代码
package facade

import "testing"

var expect = "A module running\nB module running"

// TestFacadeAPI ...
func TestFacadeAPI(t *testing.T) {
    api := NewAPI()
    ret := api.Test()
    if ret != expect {
        t.Fatalf("expect %s, return %s", expect, ret)
    }
}
相关推荐
Hello.Reader2 小时前
Go-Elasticsearch v9 安装与版本兼容性
elasticsearch·golang·jenkins
五岁小孩2 小时前
实操使用 go pprof 对生产环境进行性能分析(问题定位及代码优化)
性能优化·golang·pprof
永卿0014 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式
使二颗心免于哀伤4 小时前
《设计模式之禅》笔记摘录 - 10.装饰模式
笔记·设计模式
一杯科技拿铁7 小时前
Go 的时间包:理解单调时间与挂钟时间
开发语言·后端·golang
线程A8 小时前
Go 语言函数设计原则:避免修改传入参数
golang
Amagi.9 小时前
Java设计模式-建造者模式
java·设计模式·建造者模式
猫头虎11 小时前
2025年02月11日 Go生态洞察:Go 1.24 发布亮点全面剖析
开发语言·后端·python·golang·go·beego·go1.19
Python涛哥14 小时前
go语言基础教程:【2】基础语法:基本数据类型(整形和浮点型)
android·开发语言·golang
ん贤14 小时前
GMP模型
运维·服务器·后端·golang