[设计模式 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)
    }
}
相关推荐
快乐的划水a34 分钟前
组合模式及优化
c++·设计模式·组合模式
apocelipes2 小时前
下划线字段在golang结构体中的应用
golang
Zyy~2 小时前
《设计模式》装饰模式
java·设计模式
落霞的思绪5 小时前
Java设计模式详细解读
java·开发语言·设计模式
是2的10次方啊5 小时前
🚀 JDK设计模式大揭秘:23种模式藏在你每天在用的类里
设计模式
步行cgn5 小时前
设计模式(Design Patterns)
设计模式
Zyy~12 小时前
《设计模式》代理模式
设计模式·代理模式
o0向阳而生0o12 小时前
93、23种设计模式之抽象工厂模式
设计模式·抽象工厂模式
Python私教13 小时前
从“Hello World”到“高并发中间件”:Go 语言 2025 系统学习路线图
学习·中间件·golang
Tadas-Gao13 小时前
Java设计模式全景解析:从演进历程到创新实践
java·开发语言·微服务·设计模式·云原生·架构·系统架构