实现观察者模式示例,添加观察者、目标及具体实现,增强代码可读性
This commit is contained in:
parent
5022b481a4
commit
5ddda4ee95
|
|
@ -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("=========== 观察者模式结束 ===========")
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
"""
|
||||
实例:
|
||||
汤宝宝一时想不开,当了房产中介。
|
||||
一旦片区内有房东发布了新房源信息,他就会第一时间通知所有潜在租客。
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
# 抽象观察者类
|
||||
class Observer(ABC):
|
||||
@abstractmethod
|
||||
def update(self):
|
||||
pass
|
||||
|
||||
|
||||
# 抽象目标接口
|
||||
class Subject(ABC):
|
||||
@abstractmethod
|
||||
def attach(self, observer: Observer):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def detach(self, observer: Observer):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def notify(self):
|
||||
pass
|
||||
|
||||
|
||||
# 具体目标类
|
||||
class HousingAgency(Subject):
|
||||
def __init__(self):
|
||||
self._observers = []
|
||||
|
||||
def attach(self, observer: Observer):
|
||||
self._observers.append(observer)
|
||||
|
||||
def detach(self, observer: Observer):
|
||||
self._observers.remove(observer)
|
||||
|
||||
def notify(self):
|
||||
print("房产中介通知了所有租客。")
|
||||
for observer in self._observers:
|
||||
observer.update()
|
||||
|
||||
|
||||
# 具体观察者类
|
||||
class Tenant(Observer):
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
|
||||
def update(self):
|
||||
print(f"租客{self.name}收到房源更新通知!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("============= 观察者模式 =============")
|
||||
|
||||
agency = HousingAgency()
|
||||
tenant1 = Tenant("小明")
|
||||
tenant2 = Tenant("小红")
|
||||
|
||||
print("小红和小明订阅了房产中介的房源信息。")
|
||||
agency.attach(tenant1)
|
||||
agency.attach(tenant2)
|
||||
|
||||
print("房源上新了!")
|
||||
agency.notify()
|
||||
|
||||
print("-----")
|
||||
print("小红不想再接收房源信息,退订了。")
|
||||
agency.detach(tenant2)
|
||||
print("又有新房源了!")
|
||||
agency.notify()
|
||||
|
||||
print("\n=========== 观察者模式结束 ===========")
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
/*
|
||||
实例:
|
||||
汤宝宝一时想不开,当了房产中介。
|
||||
一旦片区内有房东发布了新房源信息,他就会第一时间通知所有潜在租客。
|
||||
*/
|
||||
|
||||
// 观察者抽象接口
|
||||
interface Observer {
|
||||
update(): void;
|
||||
}
|
||||
|
||||
// 目标抽象接口
|
||||
interface Subject {
|
||||
attach(observer: Observer): void;
|
||||
detach(observer: Observer): void;
|
||||
notify(): void;
|
||||
}
|
||||
|
||||
// 具体目标类
|
||||
class HousingAgency implements Subject {
|
||||
private observers: Observer[];
|
||||
|
||||
constructor() {
|
||||
this.observers = [];
|
||||
}
|
||||
|
||||
attach(observer: Observer): void {
|
||||
const isExist = this.observers.includes(observer);
|
||||
if (isExist) {
|
||||
return console.log("Observer has been attached already.");
|
||||
}
|
||||
this.observers.push(observer);
|
||||
}
|
||||
|
||||
detach(observer: Observer): void {
|
||||
const observerIndex = this.observers.indexOf(observer);
|
||||
if (observerIndex === -1) {
|
||||
return console.log("Nonexistent observer.");
|
||||
}
|
||||
this.observers.splice(observerIndex, 1);
|
||||
}
|
||||
|
||||
notify(): void {
|
||||
console.log("房产中介通知了所有租客。");
|
||||
for (const observer of this.observers) {
|
||||
observer.update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 具体观察者类
|
||||
class TenantObs implements Observer {
|
||||
private name: string;
|
||||
|
||||
constructor(name: string) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
update(): void {
|
||||
console.log(`租客${this.name}收到了房源更新通知。`);
|
||||
}
|
||||
}
|
||||
|
||||
(function () {
|
||||
console.log("============= 观察者模式 =============");
|
||||
const agency = new HousingAgency();
|
||||
const tenant1 = new TenantObs("小明");
|
||||
const tenant2 = new TenantObs("小红");
|
||||
console.log("小红和小明订阅了房产中介的房源信息。");
|
||||
agency.attach(tenant1);
|
||||
agency.attach(tenant2);
|
||||
console.log("房源上新了!");
|
||||
agency.notify();
|
||||
|
||||
console.log("-----");
|
||||
console.log("小红不想再接收房源信息,退订了。");
|
||||
agency.detach(tenant2);
|
||||
console.log("又有新房源了!");
|
||||
agency.notify();
|
||||
|
||||
console.log("\n=========== 观察者模式结束 ===========");
|
||||
})();
|
||||
Loading…
Reference in New Issue