实现观察者模式示例,添加观察者、目标及具体实现,增强代码可读性
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
/*
|
||||
实例:
|
||||
汤宝宝一时想不开,当了房产中介。
|
||||
一旦片区内有房东发布了新房源信息,他就会第一时间通知所有潜在租客。
|
||||
*/
|
||||
|
||||
// 观察者抽象接口
|
||||
type Observer interface {
|
||||
Update()
|
||||
}
|
||||
|
||||
// 目标抽象接口
|
||||
type Subject interface {
|
||||
Attach(observer Observer)
|
||||
Detach(observer Observer)
|
||||
Notify()
|
||||
}
|
||||
|
||||
// 具体目标 - 房产中介
|
||||
type HousingAgency struct {
|
||||
observers []Observer
|
||||
}
|
||||
|
||||
func (h *HousingAgency) Attach(observer Observer) {
|
||||
h.observers = append(h.observers, observer)
|
||||
}
|
||||
|
||||
func (h *HousingAgency) Detach(observer Observer) {
|
||||
for i, obs := range h.observers {
|
||||
if obs == observer {
|
||||
h.observers = append(h.observers[:i], h.observers[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HousingAgency) Notify() {
|
||||
fmt.Println("房产中介通知了所有租客。")
|
||||
for _, observer := range h.observers {
|
||||
observer.Update()
|
||||
}
|
||||
}
|
||||
|
||||
// 具体观察者 - 租客
|
||||
type Tenant struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (t *Tenant) Update() {
|
||||
fmt.Printf("租客%s收到了房源更新通知。\n", t.name)
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("============= 观察者模式 =============")
|
||||
|
||||
agency := &HousingAgency{}
|
||||
|
||||
tenant1 := &Tenant{name: "小明"}
|
||||
tenant2 := &Tenant{name: "小红"}
|
||||
|
||||
fmt.Println("小红和小明订阅了房产中介的房源信息。")
|
||||
agency.Attach(tenant1)
|
||||
agency.Attach(tenant2)
|
||||
fmt.Println("房源上新了!")
|
||||
agency.Notify()
|
||||
|
||||
fmt.Println("-----")
|
||||
fmt.Println("小红不想再接收房源信息,退订了。")
|
||||
agency.Detach(tenant2)
|
||||
fmt.Println("又有新房源了!")
|
||||
agency.Notify()
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("=========== 观察者模式结束 ===========")
|
||||
}
|
||||
Reference in New Issue
Block a user