//观察者模式
//被观察者接口
type subject interface{
Notify() //通知
Reg(ob obeserver) //注册
SetState(state string) //状态
GetState()//查看状态
}
//观察者接口
type obeserver interface {
Update(string) //更新自身状态
}
//被观察者
type subject1 struct{
State string
Obers []obeserver
}
//观察者1
type ober1 struct{
State string
}
//观察者2
type ober2 struct{
State string
}
//通知
func (this *subject1)Notify(){
for _,v:=range this.Obers{
v.Update(this.State)
}
}
//注册
func (this *subject1)Reg(ob obeserver){
this.Obers=append(this.Obers, ob)
}
//更新
func (this *subject1)SetState(state string){
this.State=state
}
//查看状态
func (this *subject1)GetState()string{
return this.State
}
//更新
func (this *ober1)Update(st string){
this.State=st
fmt.Println("ober1的状态更新为",st)
}
func (this *ober2)Update(st string){
this.State=st
fmt.Println("ober2的状态更新为",st)
}
func main(){
sub:=&subject1{}
ob1:=&ober1{}
ob2:=&ober2{}
sub.Reg(ob1)
sub.Reg(ob2)
sub.SetState("快乐无限")
sub.Notify()
}