在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
相关推荐
S***t7149 分钟前
Vue面试经验
javascript·vue.js·面试
粉末的沉淀37 分钟前
css:制作带边框的气泡框
前端·javascript·css
p***h6432 小时前
JavaScript在Node.js中的异步编程
开发语言·javascript·node.js
N***73852 小时前
Vue网络编程详解
前端·javascript·vue.js
q***38513 小时前
TypeScript 与后端开发Node.js
javascript·typescript·node.js
Nan_Shu_6144 小时前
学习:Sass
javascript·学习·es6
WYiQIU4 小时前
面了一次字节前端岗,我才知道何为“造火箭”的极致!
前端·javascript·vue.js·react.js·面试
qq_316837754 小时前
uniapp 观察列表每个元素的曝光时间
前端·javascript·uni-app
小夏同学呀4 小时前
在 Vue 2 中实现 “点击下载条码 → 打开新窗口预览 → 自动唤起浏览器打印” 的功能
前端·javascript·vue.js
芳草萋萋鹦鹉洲哦4 小时前
【vue】导航栏变动后刷新router的几种方法
前端·javascript·vue.js