11.Golang設(shè)計模式之外觀模式

外觀模式

GitHub代碼鏈接
外觀模式(Facade Pattern)隱藏系統(tǒng)的復(fù)雜性,并向客戶端提供了一個客戶端可以訪問的接口。

什么是外觀模式

外觀模式為子系統(tǒng)中的一組接口提供一個一致的界面,這個接口使得這一子系統(tǒng)更加容易使用。

解決了什么問題

降低子系統(tǒng)訪問的復(fù)雜性,簡化客戶端與子系統(tǒng)之間的接口。

優(yōu)點

  • 減少系統(tǒng)間的相互依賴
  • 提高靈活性
  • 提高安全性

缺點

  • 不符合開閉原則

代碼實現(xiàn)

創(chuàng)建三個模型實例,使用一個外觀類來包含這三個模型實例,使得用戶可以通過外觀類使用統(tǒng)一的接口來調(diào)用這三個模型實例。

1.1 模型實例創(chuàng)建

//Shape 模型接口
type Shape interface {
    Draw()
}

//Circle 圓形類
type Circle struct{}

//Rectangle 矩形類
type Rectangle struct{}

//Square 正方形類
type Square struct{}

//NewCircle 實例化圓形類
func NewCircle() *Circle {
    return &Circle{}
}

//Draw 實現(xiàn)Shape接口
func (c *Circle) Draw() {
    fmt.Println("Circle Draw method.")
}

1.2 外觀類實現(xiàn)

//ShapeMaker 外觀類
type ShapeMaker struct {
    circle    Circle
    square    Square
    rectangle Rectangle
}

//NewShapeMaker 實例化外觀類
func NewShapeMaker() *ShapeMaker {
    return &ShapeMaker{
        circle:    Circle{},
        rectangle: Rectangle{},
        square:    Square{},
    }
}

//DrawCircle 調(diào)用circle的Draw方法
func (shapeMk *ShapeMaker) DrawCircle() {
    shapeMk.circle.Draw()
}

//DrawRectangle 調(diào)用rectangle的Draw方法
func (shapeMk *ShapeMaker) DrawRectangle() {
    shapeMk.rectangle.Draw()
}

//DrawSquare 條用square的Draw方法
func (shapeMk *ShapeMaker) DrawSquare() {
    shapeMk.square.Draw()
}

上一篇

10.Golang設(shè)計模式之裝飾器模式

下一篇

12.Golang設(shè)計模式之享元模式

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容