Go:常见的几种设计模式解析

93 阅读2分钟

在软件工程中,设计模式是解决常见问题的一套经典解决方案。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
}

UML 模型:

image.png

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 模型:

image.png

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 模型:

image.png

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() {
    // 实现具体逻辑
}

UML 模型:

image.png

以上介绍的四种设计模式在 Go 语言中的实现展示了如何在没有类和继承的条件下,通过接口和结构体实现设计模式的核心原则和目标。通过这些模式,Go 语言的开发者可以更好地组织和模块化代码,提高软件的可维护性和扩展性。