Go语言设计模式综合应用:从理论到实战案例
Go语言设计模式综合应用从理论到实战案例引言设计模式是解决软件设计问题的经典方案。Go语言虽然没有类继承等传统OOP特性但通过接口、组合等机制可以实现各种设计模式。本文将深入探讨Go语言中的设计模式实现结合实际案例展示如何在项目中应用这些模式。一、创建型模式1.1 单例模式package singleton import ( sync ) type Singleton struct { data string } var instance *Singleton var once sync.Once func GetInstance() *Singleton { once.Do(func() { instance Singleton{ data: initial data, } }) return instance } func (s *Singleton) SetData(data string) { s.data data } func (s *Singleton) GetData() string { return s.data }1.2 工厂模式package factory type Product interface { GetName() string } type ConcreteProductA struct{} func (p *ConcreteProductA) GetName() string { return Product A } type ConcreteProductB struct{} func (p *ConcreteProductB) GetName() string { return Product B } type Factory struct{} func (f *Factory) CreateProduct(typeName string) Product { switch typeName { case A: return ConcreteProductA{} case B: return ConcreteProductB{} default: return nil } }1.3 建造者模式package builder type Product struct { PartA string PartB string PartC string } type Builder interface { BuildPartA() BuildPartB() BuildPartC() GetProduct() *Product } type ConcreteBuilder struct { product *Product } func NewConcreteBuilder() *ConcreteBuilder { return ConcreteBuilder{ product: Product{}, } } func (b *ConcreteBuilder) BuildPartA() { b.product.PartA Part A } func (b *ConcreteBuilder) BuildPartB() { b.product.PartB Part B } func (b *ConcreteBuilder) BuildPartC() { b.product.PartC Part C } func (b *ConcreteBuilder) GetProduct() *Product { return b.product } type Director struct { builder Builder } func (d *Director) Construct() *Product { d.builder.BuildPartA() d.builder.BuildPartB() d.builder.BuildPartC() return d.builder.GetProduct() }二、结构型模式2.1 适配器模式package adapter type Target interface { Request() string } type Adaptee struct{} func (a *Adaptee) SpecificRequest() string { return Specific request } type Adapter struct { adaptee *Adaptee } func (a *Adapter) Request() string { return a.adaptee.SpecificRequest() }2.2 装饰器模式package decorator type Component interface { Operation() string } type ConcreteComponent struct{} func (c *ConcreteComponent) Operation() string { return Base operation } type Decorator struct { component Component } func (d *Decorator) Operation() string { return d.component.Operation() } type ConcreteDecoratorA struct { Decorator } func (d *ConcreteDecoratorA) Operation() string { return Decorator A( d.component.Operation() ) } type ConcreteDecoratorB struct { Decorator } func (d *ConcreteDecoratorB) Operation() string { return Decorator B( d.component.Operation() ) }2.3 代理模式package proxy type Subject interface { Request() } type RealSubject struct{} func (r *RealSubject) Request() { // 实际操作 } type Proxy struct { realSubject *RealSubject } func (p *Proxy) Request() { // 前置处理 if p.realSubject nil { p.realSubject RealSubject{} } p.realSubject.Request() // 后置处理 }三、行为型模式3.1 策略模式package strategy type Strategy interface { Execute(a, b int) int } type AddStrategy struct{} func (s *AddStrategy) Execute(a, b int) int { return a b } type MultiplyStrategy struct{} func (s *MultiplyStrategy) Execute(a, b int) int { return a * b } type Context struct { strategy Strategy } func (c *Context) SetStrategy(strategy Strategy) { c.strategy strategy } func (c *Context) ExecuteStrategy(a, b int) int { return c.strategy.Execute(a, b) }3.2 观察者模式package observer type Subject interface { Attach(observer Observer) Detach(observer Observer) Notify() } type Observer interface { Update(message string) } type ConcreteSubject struct { observers []Observer state string } func (s *ConcreteSubject) Attach(observer Observer) { s.observers append(s.observers, observer) } func (s *ConcreteSubject) Detach(observer Observer) { for i, o : range s.observers { if o observer { s.observers append(s.observers[:i], s.observers[i1:]...) break } } } func (s *ConcreteSubject) Notify() { for _, observer : range s.observers { observer.Update(s.state) } } func (s *ConcreteSubject) SetState(state string) { s.state state s.Notify() } type ConcreteObserver struct { name string } func (o *ConcreteObserver) Update(message string) { // 处理更新 }3.3 命令模式package command type Command interface { Execute() Undo() } type Receiver struct{} func (r *Receiver) Action() { // 执行动作 } func (r *Receiver) ReverseAction() { // 撤销动作 } type ConcreteCommand struct { receiver *Receiver } func (c *ConcreteCommand) Execute() { c.receiver.Action() } func (c *ConcreteCommand) Undo() { c.receiver.ReverseAction() } type Invoker struct { command Command } func (i *Invoker) SetCommand(command Command) { i.command command } func (i *Invoker) Execute() { i.command.Execute() } func (i *Invoker) Undo() { i.command.Undo() }四、实战案例电商订单系统package order type OrderState interface { Handle(order *Order) error } type CreatedState struct{} func (s *CreatedState) Handle(order *Order) error { order.State PaidState{} return nil } type PaidState struct{} func (s *PaidState) Handle(order *Order) error { order.State ShippedState{} return nil } type ShippedState struct{} func (s *ShippedState) Handle(order *Order) error { order.State CompletedState{} return nil } type CompletedState struct{} func (s *CompletedState) Handle(order *Order) error { return errors.New(order is already completed) } type Order struct { ID string State OrderState } func NewOrder(id string) *Order { return Order{ ID: id, State: CreatedState{}, } } func (o *Order) Process() error { return o.State.Handle(o) }五、设计模式选择指南问题场景推荐模式需要确保类只有一个实例单例模式需要创建复杂对象建造者模式需要根据条件创建不同对象工厂模式需要兼容不兼容的接口适配器模式需要动态添加功能装饰器模式需要控制访问代理模式需要封装算法策略模式需要通知多个对象观察者模式需要封装请求命令模式结论设计模式是解决常见设计问题的有效工具。Go语言通过接口和组合机制可以优雅地实现各种设计模式。在实际项目中需要根据具体需求选择合适的模式避免过度设计。理解设计模式的本质和适用场景是成为优秀开发者的重要一步。