设计模式不分语言,是一种思维层面的体现,但是不能在不同语言中使用同一套实现(每种语言有不同的特性),比如go,本身是没有继承一说,但是通过结构体的组合来实现语义上的继承。而多态也是通过接口的方式来实现的。
下方的图来自于大佬博客,贴在这里方便查看!!!
设计原则
设计模式
行为型模式
观察者模式
观察者模式:发布订阅模式,理解起来比较方便。
定义:在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知。
实现方式:
- 同步阻塞
- 异步非阻塞
- 同进程
- 跨进程--------消息队列
示例基础代码
type ISubject interface {
Register(observer IObserver)
Remove(observer IObserver)
Notify(msg string)
}
//监视主体
type Subject struct {
observers []IObserver
}
//观察者统一接口
type IObserver interface {
execute(msg string)
}
//将观察者实现类注册进观察主体
func (s *Subject) Register(observer IObserver) {
s.observers = append(s.observers, observer)
}
func (s *Subject) Remove(observer IObserver) {
for i, iObserver := range s.observers {
if observer == iObserver {
s.observers = append(s.observers[:i], s.observers[i+1:]...)
}
}
}
func (s *Subject) Notify(msg string) {
for _, observer := range s.observers {
observer.execute(msg)
}
}
//模拟观察者实现类
type Observer1 struct {
}
func (o *Observer1) execute(msg string) {
fmt.Println("Observer1执行了:"+msg)
}
type Observer2 struct {
}
func (o *Observer2) execute(msg string) {
fmt.Println("Observer2执行了:"+msg)
}
模拟EventBus
- 异步非阻塞
- 支持任意参数
- 支持任意自定义函数
//提供发布订阅的接口
type Bus interface {
Subscribe(topic string, handler interface{}) error
Publish(topic string, args ...interface{})
}
//实现异步消息总线
type AsyncEventBus struct {
handlers map[string][]reflect.Value
lock sync.Mutex
}
//初始化消息总线
func NewEventBus() *AsyncEventBus {
return &AsyncEventBus{
handlers: make(map[string][]reflect.Value),
lock: sync.Mutex{},
}
}
func (a *AsyncEventBus) Subscribe(topic string, handler interface{}) error {
a.lock.Lock()
defer a.lock.Unlock()
value := reflect.ValueOf(handler)
if value.Type().Kind() != reflect.Func {
return fmt.Errorf("handler is not function")
}
_, ok := a.handlers[topic]
if !ok {
//没有该topic,则新建
a.handlers[topic] = make([]reflect.Value,0)
}
//相当于用链表串起来订阅相同topic的方式
a.handlers[topic] = append(a.handlers[topic],value)
return nil
}
func (a *AsyncEventBus) Publish(topic string, args ...interface{}) {
handlers, ok := a.handlers[topic]
if !ok {
//没有该topic,则返回
fmt.Println("not have this topic: "+topic)
return
}
//反射参数
params := make([]reflect.Value,len(args))
for i, arg := range args {
params[i] = reflect.ValueOf(arg)
}
for _, handler := range handlers {
//异步执行
go handler.Call(params)
}
}