在工厂生产中,其中产品生产后,会需要多个人去质检,那么质检员是时时刻刻去检查产品的状态,还是产品做好了,去通知质检员呢,如果按照质检员去检查,去轮训,这样会浪费性能,需要不断的去检查,那么我们就可以使用观察者模式
观察者模式需要三个条件:观察者 被观察,话题订阅
接下来用代码实现
package main
import "fmt"
//定义产品, 质检员监听产品,如果产品好了,就进行下一步
type Product struct {
observers []Observer //质检员
context string
}
func NewSubject() *Product {
return &Product{
observers: make([]Observer, 0),
}
}
//质检员加入产品的监听
func (s *Product) Attach(o Observer) {
s.observers = append(s.observers, o)
}
//通知质检员
func (s *Product) notify() {
for _, o := range s.observers {
o.Update(s)
}
}
func (s *Product) UpdateContext(context string) {
//改变产品的状态
s.context = context
s.notify()
}
type Observer interface {
Update(*Product)
}
//定义质检员
type Inspect struct {
name string
}
func NewInspect(name string) *Inspect {
return &Inspect{
name: name,
}
}
func (i *Inspect) Update(s *Product) {
fmt.Println(i.name + "观察到" + s.context)
fmt.Println("质检员来检查咯")
}
func main() {
product := NewSubject()
inspect1 := NewInspect("inspect1")
inspect2 := NewInspect("inspect2")
inspect3 := NewInspect("inspect3")
product.Attach(inspect1)
product.Attach(inspect2)
product.Attach(inspect3)
product.UpdateContext("observer change")
}
效果: