当前位置:网站首页>Observer mode

Observer mode

2022-06-24 09:51:00 Time202051

//  The theme   newspaper office 
class Subject {
    
    constructor(name) {
    
        this.name = name
        this.news = "" // The contents published by the newspaper office , It will be published to all subscribers who have subscribed to the newspaper 
        this.observers = []  // User array 
    }
    add(observer) {
    
        this.observers.push(observer)
    }
    getState() {
    
        return this.news
    }
    setState(news) {
    
        this.news = news
        //  Publish a new newspaper , Publish to all users immediately 
        this.notify()
    }
    notify() {
    
        this.observers.forEach(item => {
    
            item.update(this) // Trigger... For all subscribers update
            console.log('---------------');
        })
    }

}

//  The observer   user   It is known that / Unknown users 
class Observer {
    
    constructor(name, subject) {
    
        this.name = name  // user name 
        this.subject = subject
        this.subject.add(this) // Users give their information to newspapers ( Only then did the newspaper know who the subscribers were )
    }
    update(e) {
    
        console.log(this.subject.name+"  To the messenger  " + this.name + "  Sent a newspaper with the content of : " + this.subject.getState());
    }
}

//  One to many   A newspaper office corresponds to multiple users 
let bs = new Subject(' The xinhua news agency ')
let lts = new Subject(" (Reuters) - ")
let zs = new Observer(' Frenchman Zhang San ', bs)
let ls = new Observer(" Li Si ", bs) // Li Si also subscribed to the newspaper 
let ww = new Observer(" Wang Wu ", bs) // Wang Wu also subscribed to the newspaper 
let zl = new Observer(" Zhao Liu ",lts)
let mq = new Observer(" Horse seven ",lts)

//  Newspapers publish newspapers 
let new1 = bs.setState(" Hello, everyone. I'm a newspaper , Thank you for subscribing to our newspaper ")
let new2 = bs.setState(" The first issue of the newspaper office ")
let ltsNew1 = lts.setState(" Here is the latest Reuters report ")
console.log(new1);
console.log(new2);
console.log(ltsNew1);
原网站

版权声明
本文为[Time202051]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240903259354.html