/*三个观察者:音乐、动画、文字,通过观察HP变化做出相应反应 */
//定义hp观察者接口
interface Ihp_ob{
hp_change(HP:number):void;
}
//定义观察主题接口
interface Isubject_ob{
//添加观察者和删除观察者功能,类型为Ihp_ob
add_ob(observer:Ihp_ob):void;
del_ob(observer:Ihp_ob):void;
//广播方法
notify():void;
}
//实现观察主题接口,玩家角色类方法(负责传输自我状态)
class ob_subject implements Isubject_ob{
// 私有属性,存储 HP 值和观察者列表
private hp:number;
//定义个名为observers,类型为Ihp_ob的数组,用以储存观察者
observers:Ihp_ob[] = [];
constructor(_hp:number){
this.hp = _hp;
}
//实现接口的方法
add_ob(observer: Ihp_ob): void {
//将接受的observer观察者添加到数组
this.observers.push(observer);
console.log(`添加观察者成功,当前有${JSON.stringify(this.observers.length)}个观察者`);
}
del_ob(observer: Ihp_ob): void {
//查找需要删除的观察者地址
let index = this.observers.indexOf(observer);
if(index !== -1){
this.observers.splice(index,1);
console.log(`观察者${JSON.stringify(observer)}已删除,当前有${JSON.stringify(this.observers.length)}个观察者`);
}
}
//通知所有观察者 HP 值的变化
notify(): void {
for(let observer of this.observers){
observer.hp_change(this.hp);
}
}
//获取当前 HP 值
gethp(){
return this.hp;
}
//设置新的 HP 值,并通知观察者
set (hp:number){
this.hp = hp;
this.notify();
}
}
//定义观察者
class hp_obs implements Ihp_ob{
private hp_obs_name:string;
constructor(name:string){
this.hp_obs_name = name;
}
// 覆盖toString方法,方便打印
toString():string{
return this.hp_obs_name;
}
hp_change(HP: number): void {
if(HP <= 50 && HP != 0){
console.log(`${this.hp_obs_name}接收到不妙的信息`);
}else if(HP <= 0 ){
console.log(`${this.hp_obs_name}已收到玩家挂掉的消息`);
}
}
}
//创建一个玩家角色实例,初始 HP 值为 100
let player = new ob_subject(100);
//实例化观察者
let music = new hp_obs(`music`);
let animation = new hp_obs(`animation`);
let word = new hp_obs(`word`);
//将三个观察者添加到玩家角色的列表中
player.add_ob(music);
player.add_ob(animation);
player.add_ob(word);
// 测试不同的 HP 值对应的效果
player.set(50);
console.log(player.gethp())
player.set(0)
TypeScript观察者模式练习
最新推荐文章于 2024-08-27 16:58:03 发布