匠心精神 - 良心品质腾讯认可的专业机构-IT人的高薪实战学院

咨询电话:4000806560

「Golang设计模式」Golang 常见设计模式介绍

「Golang设计模式」Golang 常见设计模式介绍

Golang 作为一门新兴的编程语言,也拥有着自己的设计模式。设计模式是软件开发经验的总结和教训的体现,是能用于解决某类问题的模板或范本,它不是代码,而是一种面向对象的设计思想。本文将对 Golang 常见的设计模式进行介绍。

一. 创建型模式

1. 单例模式

单例模式是一种常见的创建型模式,它保证某个类只有一个实例,并提供一个全局访问点。在 Golang 中,单例模式可以通过 sync.Once 实现一次性的代码执行,从而保证只有一次实例化。

```go
type singleton struct{}

var instance *singleton
var once sync.Once

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

2. 工厂模式

工厂模式是一个创建对象的接口,让子类决定实例化哪一个类。在 Golang 中,工厂模式可以通过一个工厂函数实现,返回一个接口或结构体实例,隐藏了对象的创建过程。

```go
type IProduct interface {
    printProduct()
}

type ConcreteProductA struct{}

func (c *ConcreteProductA) printProduct() {
    fmt.Println("Product A")
}

type ConcreteProductB struct{}

func (c *ConcreteProductB) printProduct() {
    fmt.Println("Product B")
}

func CreateProduct(productType string) IProduct {
    switch productType {
    case "A":
        return &ConcreteProductA{}
    case "B":
        return &ConcreteProductB{}
    default:
        return nil
    }
}
```

二. 结构型模式

1. 适配器模式

适配器模式将一个类的接口转换成客户希望的另外一个接口。在 Golang 中,适配器模式可以使用接口实现,将不兼容的接口转换成需要的接口。

```go
type Target interface {
    request() string
}

type Adaptee struct {}

func (*Adaptee) specificRequest() string {
    return "Adaptee"
}

type Adapter struct {
    adaptee *Adaptee
}

func (a *Adapter) request() string {
    return a.adaptee.specificRequest()
}

func NewAdapter(adaptee *Adaptee) Target {
    return &Adapter{adaptee: adaptee}
}
```

2. 装饰器模式

装饰器模式可以在不改变原有对象结构的情况下,动态地给对象添加一些职责。在 Golang 中,装饰器模式可以使用匿名组合实现。

```go
type Component interface {
    operation() string
}

type ConcreteComponent struct {}

func (*ConcreteComponent) operation() string {
    return "ConcreteComponent"
}

type Decorator struct {
    component Component
}

func (d *Decorator) operation() string {
    return d.component.operation()
}

type ConcreteDecoratorA struct {
    Decorator
}

func (c *ConcreteDecoratorA) operation() string {
    return "ConcreteDecoratorA " + c.component.operation()
}

type ConcreteDecoratorB struct {
    Decorator
}

func (c *ConcreteDecoratorB) operation() string {
    return "ConcreteDecoratorB " + c.component.operation()
}
```

三. 行为型模式

1. 策略模式

策略模式定义一系列算法,将它们封装起来,并且使它们可以相互替换。在 Golang 中,策略模式可以通过接口实现。

```go
type Strategy interface {
    doStrategy() string
}

type Context struct {
    strategy Strategy
}

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

func (c *Context) execute() string {
    return c.strategy.doStrategy()
}

type ConcreteStrategyA struct{}

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

type ConcreteStrategyB struct{}

func (*ConcreteStrategyB) doStrategy() string {
    return "Strategy B"
}
```

2. 观察者模式

观察者模式定义了一个一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。在 Golang 中,观察者模式可以使用 channel 和 goroutine 实现。

```go
type IObserver interface {
    update(msg string)
}

type ISubject interface {
    register(observer IObserver)
    unregister(observer IObserver)
    notifyAll()
}

type Subject struct {
    observers []IObserver
}

func (s *Subject) register(observer IObserver) {
    s.observers = append(s.observers, observer)
}

func (s *Subject) unregister(observer IObserver) {
    for i, o := range s.observers {
        if o == observer {
            s.observers = append(s.observers[:i], s.observers[i+1:]...)
            break
        }
    }
}

func (s *Subject) notifyAll(msg string) {
    for _, o := range s.observers {
        go o.update(msg)
    }
}

type ConcreteObserverA struct{}

func (*ConcreteObserverA) update(msg string) {
    fmt.Println("Observer A : ", msg)
}

type ConcreteObserverB struct{}

func (*ConcreteObserverB) update(msg string) {
    fmt.Println("Observer B : ", msg)
}
```

以上就是 Golang 常见的设计模式介绍了。设计模式在实际编程中具有重要的意义,它能提高代码的质量、可维护性和可扩展性,值得我们深入学习和应用。