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

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);
相关推荐
DKPT6 小时前
Java设计模式之行为型模式(观察者模式)介绍与说明
java·笔记·学习·观察者模式·设计模式
络77 小时前
Java4种设计模式详解(单例模式、工厂模式、适配器模式、代理模式)
单例模式·设计模式·代理模式·适配器模式·工厂模式
贱贱的剑7 小时前
5.适配器模式
设计模式·适配器模式
JouJz8 小时前
设计模式之工厂模式:对象创建的智慧之道
java·jvm·设计模式
极光雨雨10 小时前
【设计模式】备忘录模式(标记(Token)模式)
设计模式·备忘录模式
Codebee10 小时前
OneCode 3.0: 注解驱动的Spring生态增强方案
后端·设计模式·架构
极光雨雨12 小时前
【设计模式】策略模式(政策(Policy)模式)
设计模式·bash·策略模式
小刘|12 小时前
单例模式详解
java·开发语言·单例模式
vvilkim13 小时前
深入理解观察者模式:构建松耦合的交互系统
观察者模式·设计模式
CodeWithMe14 小时前
【读书笔记】《C++ Software Design》第十章与第十一章 The Singleton Pattern & The Last Guideline
开发语言·c++·设计模式