外觀模式
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()
}