Go設計模式執行個體:簡單工廠

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
該系列文章將用簡單的例子來介紹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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.