【设计模式】工厂模式、单例模式、观察者模式、发布订阅模式

1.工厂模式

javascript 复制代码
class Factory{
    createProduct(name){
        return new Product(name);
    }
}
class Product{
    constructor(name){
        this.name=name;
    }
    display(){
        console.log(`product:${this.name}`);
    }
}

//使用
const factory=new Factory();
const p1=factory.createProduct('P1');
const p2=factory.createProduct('P2');
p1.display()
p2.display()

2.单例模式

javascript 复制代码
class Singleton{
    static instance=null;
    constructor(){
        if(Singleton.instance){
            return Singleton.instance
        }
        Singleton.instance=this;
    }
}

//使用
const instance1=new Singleton()
const instance2=new Singleton()

3.观察者模式

javascript 复制代码
class Subject{
    constructor(){
        this.observers=[];
    }
    addObserver(observer){
        this.observers.push(observer);
    }
    removerObserver(observer){
        this.observers=this.observers.filter(obs=>obs!==observer);
    }
    notifyObserver(){
        this.observers.forEach(obs=>obs.update());
    }
}

class Observer{
    constructor(name){
        this.name=name;
    }
    update(){
        console.log(`Observer ${this.name} has been notified`);
    }
}
//使用
const subject=new Subject();
const observer1=new Observer('1');
const observer2=new Observer('2');
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notifyObserver();

4.发布订阅模式

javascript 复制代码
class Broker{
    constructor(){
        this.subscribers=[];
        this.state=0;
    }
    subscribe(subscriber){
        this.subscribers.push(subscriber);
    }
    setState(state){
        this.state=state;
        this.publish();
    }
    getState(){
        return this.state;
    }
    publish(){
        this.subscribers.forEach(sub=>sub.update());
    }
}

class Publisher{
    constructor(){}
    changeState(broker,state){
        broker.setState(state);
    }
}

class Subscriber{
    constructor(name,broker){
        this.name=name;
        this.broker=broker;
        this.broker.subscribe(this);
    }
    update(){
        console.log(`${this.name}:${this.broker.getState()}`);
    }
}
//使用
const broker=new Broker();
const publish=new Publisher();
const subscribe1=new Subscriber('s1',broker);
const subscribe2=new Subscriber('s2',broker);
publish.changeState(broker,1);
相关推荐
周努力.1 小时前
设计模式之中介者模式
设计模式·中介者模式
yangyang_z17 小时前
【C++设计模式之Template Method Pattern】
设计模式
源远流长jerry18 小时前
常用设计模式
设计模式
z263730561118 小时前
六大设计模式--OCP(开闭原则):构建可扩展软件的基石
设计模式·开闭原则
01空间1 天前
设计模式简述(十八)享元模式
设计模式·享元模式
秋名RG1 天前
深入理解设计模式之原型模式(Prototype Pattern)
设计模式·原型模式
熬夜学编程的小王1 天前
【Linux篇】高并发编程终极指南:线程池优化、单例模式陷阱与死锁避坑实战
linux·单例模式·线程池·线程安全
Li小李同学Li2 天前
设计模式【cpp实现版本】
单例模式·设计模式
周努力.2 天前
设计模式之状态模式
设计模式·状态模式
268572592 天前
Java 23种设计模式 - 行为型模式11种
java·开发语言·设计模式