在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern)

确保一个类只有一个实例,并提供一个全局访问点。

示例代码:

复制代码
class Singleton {
    constructor() {
        if (Singleton.instance) {
            return Singleton.instance;
        }
        Singleton.instance = this;
        this.data = [];
    }

    addData(value) {
        this.data.push(value);
    }

    getData() {
        return this.data;
    }
}

const singleton1 = new Singleton();
const singleton2 = new Singleton();

singleton1.addData('value1');

console.log(singleton1.getData()); // ['value1']
console.log(singleton2.getData()); // ['value1'] - Both are the same instance

2. 策略模式(Strategy Pattern)

定义一系列算法,把它们一个个封装起来,并且使它们可以互换。

示例代码:

复制代码
class Context {
    constructor(strategy) {
        this.strategy = strategy;
    }

    executeStrategy(a, b) {
        return this.strategy.execute(a, b);
    }
}

class AdditionStrategy {
    execute(a, b) {
        return a + b;
    }
}

class SubtractionStrategy {
    execute(a, b) {
        return a - b;
    }
}

const context = new Context(new AdditionStrategy());
console.log(context.executeStrategy(5, 3)); // 8

context.strategy = new SubtractionStrategy();
console.log(context.executeStrategy(5, 3)); // 2

3. 代理模式(Proxy Pattern)

为其他对象提供一种代理以控制对这个对象的访问。

示例代码:

复制代码
class RealObject {
    request() {
        console.log('Request made to RealObject');
    }
}

class Proxy {
    constructor(realObject) {
        this.realObject = realObject;
    }

    request() {
        console.log('Request intercepted by Proxy');
        this.realObject.request();
    }
}

const realObject = new RealObject();
const proxy = new Proxy(realObject);

proxy.request(); // Request intercepted by Proxy
                 // Request made to RealObject

4. 原型模式(Prototype Pattern)

通过复制现有的实例来创建新对象,而不是通过实例化新对象。

示例代码:

复制代码
class Prototype {
    constructor() {
        this.primitive = 0;
        this.object = { a: 1 };
    }

    clone() {
        const clone = Object.create(this);
        clone.object = Object.assign({}, this.object);
        return clone;
    }
}

const original = new Prototype();
original.primitive = 1;
original.object.a = 2;

const copy = original.clone();
console.log(copy.primitive); // 1
console.log(copy.object.a);  // 2
相关推荐
To_OC6 小时前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
kyriewen7 小时前
面试官问你:“AI 能写 80% 的代码了,公司为什么还需要你?”
前端·javascript·面试
Goodbye10 小时前
从 Token 到 Embedding:LLM 核心基础深度解析
javascript·人工智能
用户9385156350711 小时前
工具调用背后:LLM 如何突破“缸中大脑”,操控真实世界?
javascript·人工智能
Goodbye11 小时前
从函数到智能:LLM Tool Use 深度解析
javascript·人工智能
半个落月11 小时前
大模型到底是怎么“调用工具”的?从一个 Node.js Demo 看懂 Tool Use
javascript·人工智能
烬羽11 小时前
中英文 token 数量差一倍?两段 JS 代码搞懂 LLM 底层是怎么"读"文字的
javascript·程序员·架构
山河木马11 小时前
矩阵专题1-怎么创建模型矩阵(uModelMatrix)
javascript·webgl·计算机图形学
花椒技术11 小时前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
前端开发爱好者16 小时前
支持 110 种文件预览!兼容 Vue、React、Svelte!
前端·javascript·vue.js