[设计模式 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)
    }
}
相关推荐
float_六七2 小时前
Java——单例类设计模式
java·单例模式·设计模式
老菜鸟的每一天2 小时前
创建型模式-Prototype 模式(原型模式)
设计模式·原型模式
码熔burning2 小时前
(五)趣学设计模式 之 建造者模式!
java·设计模式·建造者模式
Villiam_AY4 小时前
goredis常见基础命令
redis·golang
PyAIGCMaster4 小时前
50周学习go语言:第四周 函数与错误处理深度解析
开发语言·学习·golang
PyAIGCMaster4 小时前
第二周补充:Go语言中&取地址符与fmt函数详解
开发语言·后端·golang
闲猫10 小时前
go orm GORM
开发语言·后端·golang
丁卯40410 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
黑不溜秋的11 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
付聪121013 小时前
策略模式介绍和代码示例
设计模式