卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64787本站已运行4123

Go框架中常见的设计模式有哪些?

go 框架中常见的 4 大设计模式分别是:单例模式:确保只有一个实例的模式,常用于控制资源访问或提供全局缓存。工厂模式:提供创建对象接口,而无需指定类,使应用程序能动态创建对象。观察者模式:定义主题和观察者,当主题状态改变时通知观察者,实现松散耦合。策略模式:定义接口,使算法行为独立于使用它的类,可在运行时切换算法。

Go框架中常见的设计模式有哪些?

Go 框架中常见的 4 大设计模式

设计模式是可重用的解决方案,用于解决软件开发中的常见问题。Go 框架中广泛使用了多种设计模式。本文将介绍 4 个最常见的模式,并提供实战案例来演示它们的应用。

1. 单例模式

单例模式确保一个类只有一个实例,并提供一个全局访问点。它通常用于控制资源访问或提供全局缓存。

实战案例:数据库连接池

// dbConnPool is a singleton instance of the database connection pool.
var dbConnPool = &DBConnPool{
    MaxConnections: 10,
    DBConnections:  make([]*sql.DB, 0, 10),
}

// New returns a new instance of *DBConnPool.
func New() *DBConnPool {
    dbConnPool = new(DBConnPool)
    return dbConnPool
}

// GetConn retrieves a connection from the pool.
func (db *DBConnPool) GetConn() (*sql.DB, error) {
    // ... logic to get a connection from the pool
}

2. 工厂模式

工厂模式提供了创建对象的接口,而无需指定具体类。这使应用程序能够动态创建对象,而不必了解底层实现。

实战案例:日志记录器

type LoggerFactory interface {
    CreateLogger(loggerType string) Logger
}

type Logger interface {
    Log(level string, message string)
}

type LoggerFactoryImpl struct {
    // ...
}

func (lf *LoggerFactoryImpl) CreateLogger(loggerType string) Logger {
    switch loggerType {
    case "console":
        return &ConsoleLogger{}
    case "file":
        return &FileLogger{}
    default:
        return &DefaultLogger{}
    }
}

func main() {
    lf := &LoggerFactoryImpl{}
    logger := lf.CreateLogger("console")
    logger.Log("INFO", "Hello world!")
}

3. 观察者模式

观察者模式定义了一个对象(主题)和多个依赖对象的集合(观察者)。当主题状态发生改变时,它会通知所有观察者。这允许松散耦合的组件对事件做出反应。

实战案例:事件处理

// Subject is the interface for an event subject.
type Subject interface {
    Attach(o Observer)
    Detach(o Observer)
    NotifyAll()
}

// Observer is the interface for an event observer.
type Observer interface {
    Update(subject Subject)
}

type EventDispatcher struct {
    observers []Observer
}

// Attach attaches an observer to the event dispatcher.
func (ed *EventDispatcher) Attach(o Observer) {
    ed.observers = append(ed.observers, o)
}

// Detach detaches an observer from the event dispatcher.
func (ed *EventDispatcher) Detach(o Observer) {
    for i, observer := range ed.observers {
        if observer == o {
            ed.observers = append(ed.observers[:i], ed.observers[i+1:]...)
            break
        }
    }
}

// NotifyAll notifies all observers.
func (ed *EventDispatcher) NotifyAll() {
    for _, observer := range ed.observers {
        observer.Update(ed)
    }
}

4. 策略模式

策略模式定义了一个接口,允许算法的行为在一个类中独立于使用它的类。这使得应用程序能够在运行时动态切换算法。

实战案例:排序算法

type SortAlgorithm interface {
    Sort(data []int)
}

type BubbleSortAlgorithm struct {
    // ...
}

func (b *BubbleSortAlgorithm) Sort(data []int) {
    // ... bubble sort algorithm logic
}

type SelectionSortAlgorithm struct {
    // ...
}

func (s *SelectionSortAlgorithm) Sort(data []int) {
    // ... selection sort algorithm logic
}

func main() {
    data := []int{5, 3, 1, 2, 4}

    // Use bubble sort
    bubbleSort := &BubbleSortAlgorithm{}
    bubbleSort.Sort(data)

    // Use selection sort
    selectionSort := &SelectionSortAlgorithm{}
    selectionSort.Sort(data)
}
卓越飞翔博客
上一篇: PHP框架的生态系统有何变化?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏