
Go语言设计模式行为型模式一、行为型模式概述行为型模式关注对象之间的通信和职责分配描述对象如何协作以及如何分配职责。Go语言中的行为型模式特点接口驱动通过接口定义行为契约并发安全考虑并发场景下的协作组合实现通过组合而非继承实现行为复用二、策略模式策略模式定义一系列算法把它们封装起来并使它们可以互相替换。package strategy type Strategy interface { Execute(a, b int) int } type AddStrategy struct{} func (a *AddStrategy) Execute(x, y int) int { return x y } type SubtractStrategy struct{} func (s *SubtractStrategy) Execute(x, y int) int { return x - y } type MultiplyStrategy struct{} func (m *MultiplyStrategy) Execute(x, y int) int { return x * y } 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) }三、观察者模式观察者模式定义对象间的一对多依赖当一个对象状态改变时所有依赖它的对象都会收到通知。package observer type Observer interface { Update(message string) } type Subject interface { Attach(observer Observer) Detach(observer Observer) Notify(message string) } type ConcreteSubject struct { observers []Observer } func (s *ConcreteSubject) Attach(observer Observer) { s.observers append(s.observers, observer) } func (s *ConcreteSubject) Detach(observer Observer) { for i, obs : range s.observers { if obs observer { s.observers append(s.observers[:i], s.observers[i1:]...) break } } } func (s *ConcreteSubject) Notify(message string) { for _, observer : range s.observers { observer.Update(message) } } type ConcreteObserver struct { name string } func (o *ConcreteObserver) Update(message string) { println(o.name received: message) }四、命令模式命令模式将请求封装成对象使你可以用不同的请求对客户进行参数化。package command type Command interface { Execute() Undo() } type Receiver struct{} func (r *Receiver) Action() { println(Receiver action) } func (r *Receiver) ReverseAction() { println(Receiver reverse action) } type ConcreteCommand struct { receiver *Receiver } func (c *ConcreteCommand) Execute() { c.receiver.Action() } func (c *ConcreteCommand) Undo() { c.receiver.ReverseAction() } type Invoker struct { history []Command } func (i *Invoker) SetCommand(command Command) { command.Execute() i.history append(i.history, command) } func (i *Invoker) Undo() { if len(i.history) 0 { command : i.history[len(i.history)-1] command.Undo() i.history i.history[:len(i.history)-1] } }五、迭代器模式迭代器模式提供一种方法顺序访问聚合对象中的各个元素而又不暴露该对象的内部表示。package iterator type Iterator interface { HasNext() bool Next() interface{} } type Iterable interface { CreateIterator() Iterator } type ConcreteIterator struct { collection []interface{} index int } func (i *ConcreteIterator) HasNext() bool { return i.index len(i.collection) } func (i *ConcreteIterator) Next() interface{} { if i.HasNext() { item : i.collection[i.index] i.index return item } return nil } type ConcreteCollection struct { items []interface{} } func (c *ConcreteCollection) CreateIterator() Iterator { return ConcreteIterator{collection: c.items} } func (c *ConcreteCollection) Add(item interface{}) { c.items append(c.items, item) }六、模板方法模式模板方法模式定义一个算法的骨架将一些步骤延迟到子类中实现。package template type AbstractClass interface { PrimitiveOperation1() PrimitiveOperation2() TemplateMethod() } type ConcreteClass struct{} func (c *ConcreteClass) PrimitiveOperation1() { println(Primitive operation 1) } func (c *ConcreteClass) PrimitiveOperation2() { println(Primitive operation 2) } func (c *ConcreteClass) TemplateMethod() { c.PrimitiveOperation1() c.PrimitiveOperation2() println(Template method completed) }七、状态模式状态模式允许对象在内部状态改变时改变它的行为对象看起来好像修改了它的类。package state type State interface { Handle(context *Context) } type ConcreteStateA struct{} func (s *ConcreteStateA) Handle(context *Context) { println(Handling in state A) context.SetState(ConcreteStateB{}) } type ConcreteStateB struct{} func (s *ConcreteStateB) Handle(context *Context) { println(Handling in state B) context.SetState(ConcreteStateA{}) } type Context struct { state State } func (c *Context) SetState(state State) { c.state state } func (c *Context) Request() { c.state.Handle(c) }八、责任链模式责任链模式使多个对象都有机会处理请求从而避免请求的发送者和接收者之间的耦合关系。package chain type Handler interface { SetNext(handler Handler) Handler Handle(request string) string } type AbstractHandler struct { next Handler } func (h *AbstractHandler) SetNext(handler Handler) Handler { h.next handler return handler } func (h *AbstractHandler) Handle(request string) string { if h.next ! nil { return h.next.Handle(request) } return No handler found } type ConcreteHandlerA struct { AbstractHandler } func (h *ConcreteHandlerA) Handle(request string) string { if request A { return Handled by Handler A } return h.AbstractHandler.Handle(request) } type ConcreteHandlerB struct { AbstractHandler } func (h *ConcreteHandlerB) Handle(request string) string { if request B { return Handled by Handler B } return h.AbstractHandler.Handle(request) }九、中介者模式中介者模式定义一个对象封装一系列对象之间的交互。package mediator type Mediator interface { Send(message string, colleague Colleague) } type Colleague interface { Send(message string) Receive(message string) } type ConcreteMediator struct { colleagues []Colleague } func (m *ConcreteMediator) AddColleague(colleague Colleague) { m.colleagues append(m.colleagues, colleague) } func (m *ConcreteMediator) Send(message string, sender Colleague) { for _, colleague : range m.colleagues { if colleague ! sender { colleague.Receive(message) } } } type ConcreteColleague struct { name string mediator Mediator } func (c *ConcreteColleague) Send(message string) { println(c.name sends: message) c.mediator.Send(message, c) } func (c *ConcreteColleague) Receive(message string) { println(c.name receives: message) }十、行为型模式实战场景日志处理责任链package chain type LogHandler interface { SetNext(handler LogHandler) LogHandler Handle(logLevel string, message string) } type BaseHandler struct { next LogHandler } func (h *BaseHandler) SetNext(handler LogHandler) LogHandler { h.next handler return handler } type DebugHandler struct { BaseHandler } func (h *DebugHandler) Handle(logLevel, message string) { if logLevel DEBUG { println([DEBUG] message) } else if h.next ! nil { h.next.Handle(logLevel, message) } } type InfoHandler struct { BaseHandler } func (h *InfoHandler) Handle(logLevel, message string) { if logLevel INFO { println([INFO] message) } else if h.next ! nil { h.next.Handle(logLevel, message) } } type ErrorHandler struct { BaseHandler } func (h *ErrorHandler) Handle(logLevel, message string) { if logLevel ERROR { println([ERROR] message) } else if h.next ! nil { h.next.Handle(logLevel, message) } }十一、总结行为型设计模式帮助我们管理对象间的通信和职责策略模式封装算法支持运行时切换观察者模式一对多依赖状态变化通知命令模式封装请求支持撤销/重做迭代器模式统一遍历集合模板方法模式定义算法骨架状态模式状态驱动行为变化责任链模式请求链式处理中介者模式封装对象间交互在Go语言中应用这些模式时要充分利用接口和组合特性保持代码的灵活性和可维护性。