這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
該系列文章將用簡單的例子來介紹Go語言設計模式的實現。
簡單原廠模式定義
- 原廠模式提供建立具體執行個體的功能,使用者無需關心其具體實現。
適用情境
- 避免用戶端知道內部的具體實現,只有工廠才能接觸實現細節。返回的執行個體可以是介面、具體類型等。
簡單一實例
package mainimport ("fmt""math")type GeometryType intconst (GeometryRect GeometryType = iotaGeometryCicle)type Geometry interface {Area() float32Perim() float32}type Rectangle struct {width, height float32}func (r *Rectangle) Area() float32 {return r.width * r.height}func (r *Rectangle) Perim() float32 {return 2*r.width + 2*r.height}type Circle struct {radius float32}func (c *Circle) Area() float32 {return math.Pi * c.radius * c.radius}func (c *Circle) Perim() float32 {return 2 * math.Pi * c.radius}type Params struct {width float32height float32radius float32}func NewGeometry(params *Params, geo GeometryType) Geometry {switch geo {case GeometryCicle:return &Circle{radius: params.radius,}case GeometryRect:return &Rectangle{height: params.height,width: params.width,}default:// type error}return nil}func main() {geo := NewGeometry(&Params{radius: 3.0}, GeometryCicle)fmt.Println(geo.Area())fmt.Println(geo.Perim())return}
簡單原廠模式的優缺點
優點
- 協助封裝,實現面向介面編程
- 讓用戶端和具體實作類別解耦
缺點
- 通過用戶端傳入的參數來選擇具體實作類別,就要求用戶端必須能夠理解參數的含義,這增加了用戶端的複雜度
- 不方便擴充子工廠
我的公眾號: EasyHacking
Go設計模式陸續更新中 github: csxuejin/go-design-patterns