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

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);
相关推荐
workflower10 小时前
具身智能研究对象:物理交互中的智能行为
设计模式·动态规划·软件工程·软件构建·scrum
折哥的程序人生 · 物流技术专研15 小时前
Java 23 种设计模式:从踩坑到精通 | 抽象工厂 —— 支付/收款如何成套创建?跨平台 UI 如何一键换肤?
java·开发语言·后端·设计模式
老码观察17 小时前
设计模式实战解读(八):代理模式——控制访问的隐形中间层
设计模式·代理模式
我爱cope18 小时前
【Agent智能体12 | 反思设计模式-使用外部反馈】
人工智能·设计模式·语言模型·职场和发展
geovindu18 小时前
python: Bounded Parallelism Pattern
开发语言·python·设计模式·有界并行模式
我爱cope19 小时前
【Agent智能体11 | 反思设计模式-评估反射的影响的方法】
人工智能·设计模式·语言模型·职场和发展
nnsix19 小时前
设计模式 - 迭代器模式 笔记
笔记·设计模式·迭代器模式
geovindu19 小时前
go: Bounded Parallelism Pattern
开发语言·后端·设计模式·golang·有界并行模式
IT策士19 小时前
第 23篇 k8s之Pod:多容器 Pod 与设计模式(Sidecar 等)
设计模式·容器·kubernetes
qq_297574672 天前
设计模式系列文章(基础篇第 11 篇):模板方法模式——定义算法骨架,实现代码复用与流程统一
算法·设计模式·模板方法模式