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

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);
相关推荐
繁华似锦respect2 小时前
C++ 设计模式之工厂模式详细介绍
java·linux·c++·网络协议·设计模式
想要成为祖国的花朵3 小时前
基于多设计模式的抽奖系统__测试报告
java·selenium·测试工具·jmeter·设计模式·测试用例·安全性测试
重铸码农荣光5 小时前
JavaScript 面向对象编程:从字面量到原型继承的深度探索
前端·javascript·设计模式
L***d6707 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
未可知7777 小时前
软件设计师(下午题2)、UML与设计模式
算法·设计模式·职场和发展·uml
繁华似锦respect7 小时前
C++ 设计模式之单例模式详细介绍
服务器·开发语言·c++·windows·visualstudio·单例模式·设计模式
xunyan62347 小时前
面向对象(下)-设计模式与单例设计模式
java·单例模式·设计模式
隔山打牛牛7 小时前
单例模式:高效实现全局唯一实例
单例模式
ZHE|张恒15 小时前
设计模式(十四)模板方法模式 — 定义流程骨架,把步骤差异留给子类
设计模式·模板方法模式
Codebee16 小时前
深度解析AI编程技术:从原理到实践,手把手教你落地
人工智能·设计模式·开源