在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
相关推荐
lzhdim1 小时前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
kyriewen5 小时前
我踩了3次同一个坑才明白:JavaScript里比0.1+0.2更隐蔽的5个数字陷阱
前端·javascript·面试
zhifou1234566 小时前
Vue基础(二)
前端·javascript·vue.js
默_笙6 小时前
🙃 我让爬虫终于看到了我的网站,后端同事说"这也行?"(下):App Router 全栈实战
前端·javascript
九九落6 小时前
JavaScript 实现北京时间精确到毫秒显示:UTC+8、Asia/Shanghai 与在线时间校准详解
开发语言·javascript·ecmascript
FEF前端团队7 小时前
小程序微信支付 V3 接入实战手册:从商户配置到前后端落地
javascript·后端·node.js
AI人工智能+电脑小能手8 小时前
大白话说Java设计模式-34-命令模式(业务实战篇)
java·spring·设计模式·命令模式·异步任务·撤销重做·事务封装
悟空瞎说8 小时前
# Dispatch(GCD)苹果官方文档 白话文讲解(Objective‑C 版本文档)
javascript
七牛开发者9 小时前
Coding Agent 如何跑稳长任务?从上下文管理到运行时状态
前端·javascript·后端
七牛开发者9 小时前
拆解 DeepSeek Harness:Profile 与 Bundle 如何装配运行时
前端·javascript·后端