在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
相关推荐
sg_knight2 分钟前
设计模式实战:模板方法模式(Template Method)
python·设计模式·模板方法模式
冬夜戏雪16 分钟前
实习面经记录(十)
java·前端·javascript
爱学习的程序媛2 小时前
【Web前端】JavaScript设计模式全解析
前端·javascript·设计模式·web
薛先生_0992 小时前
js学习语法第一天
开发语言·javascript·学习
苦瓜小生2 小时前
【前端】|【js手撕】经典高频面试题:手写实现function.call、apply、bind
java·前端·javascript
和沐阳学逆向3 小时前
我现在怎么用 CC Switch 管中转站,顺手拿 Codex 举个例子
开发语言·javascript·ecmascript
kgduu5 小时前
js之客户端存储
javascript·数据库·oracle
四千岁5 小时前
2026 最新版:WSL + Ubuntu 全栈开发环境,一篇搞定!
javascript·node.js
竹林8185 小时前
从“连接失败”到丝滑登录:我用 ethers.js 连接 MetaMask 的完整踩坑实录
前端·javascript
铭毅天下6 小时前
EasySearch Rules 规则语法速查手册
开发语言·前端·javascript·ecmascript