[Go语言]简单实现观察者模式

本文介绍了一种软件设计模式——观察者模式的应用,通过Subject和Observer接口,展示如何创建一个被观察者(Subject1)与多个观察者(Ober1, Ober2)进行状态更新的案例。主体对象负责维护状态并触发通知,观察者则接收并更新自身状态。
摘要由CSDN通过智能技术生成
//观察者模式
//被观察者接口
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()
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值