在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
相关推荐
我是Superman丶2 小时前
【技巧】前端VUE用中文方法名调用没效果的问题
前端·javascript·vue.js
斯~内克2 小时前
Vue 3 中 watch 的使用与深入理解
前端·javascript·vue.js
lqj_本人5 小时前
鸿蒙OS&UniApp制作多选框与单选框组件#三方框架 #Uniapp
前端·javascript·uni-app
SHIPKING3938 小时前
【HTML】个人博客页面
javascript·css·html
junjun.chen06069 小时前
【在qiankun模式下el-dropdown点击,浏览器报Failed to execute ‘getComputedStyle‘ on ‘Window‘: parameter 1 is not o
前端·javascript·前端框架
課代表9 小时前
AcroForm JavaScript Promise 对象应用示例: 异步加载PDF文件
开发语言·javascript·pdf·promise·对象
zm9 小时前
服务器连接多客户端
java·javascript·算法
小屁孩大帅-杨一凡10 小时前
一个简单点的js的h5页面实现地铁快跑的小游戏
开发语言·前端·javascript·css·html
purpleseashell_Lili11 小时前
配置别名路径 @
javascript·react
敲代码的 蜡笔小新12 小时前
【行为型之命令模式】游戏开发实战——Unity可撤销系统与高级输入管理的架构秘钥
unity·设计模式·架构·命令模式