Go:常見的幾種設計模式解析

在軟件工程中,設計模式是解決常見問題的一套經典解決方案。Go 語言,作爲一種強調簡潔和高效的編程語言,其設計模式同樣體現了這些理念。本文將探討 Go 語言中常見的幾種設計模式,包括單例模式、工廠模式、策略模式、觀察者模式,並用 UML 創建概念模型來直觀展示這些設計模式的結構。

1. 單例模式

單例模式確保一個類只有一個實例,並提供一個全局訪問點。在 Go 中,使用私有結構體和公有的獲取實例函數是實現單例的常見方法。

package singleton

import "sync"

type singleton struct{}

var instance *singleton
var once sync.Once

func GetInstance() *singleton {
    once.Do(func() {
        instance = &singleton{}
    })
    return instance
}

 模型:

2. 工廠模式

工廠模式提供了一個創建對象的接口,讓子類決定實例化哪一個類。Go 語言中沒有類和繼承,但可以通過接口和結構體實現相似的效果。

package factory

type Product interface {
    Use() string
}

type Factory struct{}

func (f *Factory) CreateProduct(t string) Product {
    if t == "A" {
        return &ProductA{}
    } else if t == "B" {
        return &ProductB{}
    }
    return nil
}

type ProductA struct{}

func (p *ProductA) Use() string {
    return "ProductA"
}

type ProductB struct{}

func (p *ProductB) Use() string {
    return "ProductB"
}

UML 模型:

3. 策略模式

策略模式定義了一系列的算法,並將每一個算法封裝起來,使它們可以互換。這模式讓算法的變化獨立於使用算法的客戶。

package strategy

type Strategy interface {
    Execute() string
}

type ConcreteStrategyA struct{}

func (s *ConcreteStrategyA) Execute() string {
    return "Strategy A"
}

type ConcreteStrategyB struct{}

func (s *ConcreteStrategyB) Execute() string {
    return "Strategy B"
}

type Context struct {
    strategy Strategy
}

func (c *Context) SetStrategy(strategy Strategy) {
    c.strategy = strategy
}

func (c *Context) ExecuteStrategy() string {
    return c.strategy.Execute()
}

UML 模型:

4. 觀察者模式

觀察者模式定義了對象之間的一對多依賴,當一個對象改變狀態時,所有依賴於它的對象都會收到通知並自動更新。

package observer

type Subject struct {
    observers []Observer
}

func (s *Subject) Attach(o Observer) {
    s.observers = append(s.observers, o)
}

func (s *Subject) Notify() {
    for _, observer := range s.observers {
        observer.Update()
    }
}

type Observer interface {
    Update()
}

type ConcreteObserverA struct{}

func (c *ConcreteObserverA) Update() {
    // 實現具體邏輯
}

type ConcreteObserverB struct{}

func (c *ConcreteObserverB) Update() {
    // 實現具體邏輯
}

PlantUML 模型:

以上介紹的四種設計模式在 Go 語言中的實現展示瞭如何在沒有類和繼承的條件下,通過接口和結構體實現設計模式的核心原則和目標。通過這些模式,Go 語言的開發者可以更好地組織和模塊化代碼,提高軟件的可維護性和擴展性。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/sqKjauy4MCRQGErRdle7AQ