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

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);
相关推荐
天若有情6738 小时前
自研极简C++软交互事件系统:干掉观察者模式、碾压前端事件机制
c++·观察者模式·交互·事件
看山是山_Lau10 小时前
建造者模式:复杂对象如何一步步构建
设计模式·建造者模式
计算机安禾10 小时前
【c++面向对象编程】第40篇:单例模式(Singleton)的多种C++实现
开发语言·c++·单例模式
霸道流氓气质10 小时前
业务链路追踪日志设计模式 — 从原理到实践
设计模式
nnsix1 天前
设计模式 - 建造者模式 笔记
笔记·设计模式·建造者模式
cui17875681 天前
矩阵拼团 + 复购拼团:新零售最稳的复购模式,规则简单
大数据·人工智能·设计模式·零售
百珏1 天前
[灰度发布]:全链路透传组件:APM、自研方案与 Java Agent 的实现取舍
后端·设计模式·架构
likerhood1 天前
设计模式 · 享元模式(Flyweight Pattern)java
java·设计模式·享元模式
AI大法师1 天前
从 Adobe 焕新看品牌系统升级:Logo、主色、字体与产品体验如何重新对齐
大数据·人工智能·adobe·设计模式
贵慜_Derek1 天前
《从零实现 Agent 系统》连载 03|控制循环:感知—决策—行动—反思
人工智能·设计模式·架构