golang外觀模式

golang外觀模式

API 爲facade 模塊的外觀接口,大部分代碼使用此接口簡化對facade類的訪問。

facade模塊同時暴露了a和b 兩個Module 的NewXXX和interface,其它代碼如果需要使用細節功能時可以直接調用。

facade.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
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)
}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章