浅谈golang中的观察者模式

来自一个大佬的博客,建议食用

设计模式不分语言,是一种思维层面的体现,但是不能在不同语言中使用同一套实现(每种语言有不同的特性),比如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)
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值