设计模式之观察者模式(一)

152 阅读1分钟
class Star{
    constructor(name){
        this.name = name
        this.status = ''
        this.observers = []

    }
    getStatus(){
        return this.status
    }
    setStatus(status){
        this.status = status
        this.notifyObserver()
    }
    addObservers(obs){
        this.observers.push(obs)
    }
    notifyObserver(){
        this.observers.map(item=>{
            item.update(this.status)
        })
    }
}

class Fan{
     constructor(name,star){
         this.name = name
         this.star = star
         this.star.addObservers(this)
     }
     update(status){
         console.log('status',status)
     }
}
let star = new Star('王菲')
let me = new Fan('me',star)

star.setStatus('红')