[设计模式 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)
    }
}
相关推荐
背帆10 小时前
go的interface接口底层实现
开发语言·后端·golang
敲代码的 蜡笔小新11 小时前
【行为型之命令模式】游戏开发实战——Unity可撤销系统与高级输入管理的架构秘钥
unity·设计模式·架构·命令模式
m0_5557629011 小时前
D-Pointer(Pimpl)设计模式(指向实现的指针)
设计模式
小Mie不吃饭11 小时前
【23种设计模式】分类结构有哪些?
java·设计模式·设计规范
阑梦清川15 小时前
关于Go语言的开发环境的搭建
开发语言·后端·golang
言之。15 小时前
Makefile 在 Go 项目中的实践
开发语言·elasticsearch·golang
Clown9519 小时前
go-zero(十八)结合Elasticsearch实现高效数据检索
开发语言·elasticsearch·golang
君鼎1 天前
C++设计模式——单例模式
c++·单例模式·设计模式
敲代码的 蜡笔小新1 天前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
令狐前生1 天前
设计模式学习整理
学习·设计模式