TypeScript观察者模式练习

/*三个观察者:音乐、动画、文字,通过观察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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值