设计模式在JavaScript中的应用:介绍一些常见的设计模式如观察者模式,工厂模式,策略模式等,并展示如何在JavaScript中实现

1、观察者模式:观察者模式是一种在项目中创建可观察者的方法,以便在对象之间实现好的通信机制。

在JavaScript中我们可以使用EventEmitter类来实现观察者模式。

复制代码
class EventEmitter {
    constructor() {
        this.events = {};
    }
  
    on(type, listener) {
        this.events[type] = this.events[type] || [];
        this.events[type].push(listener);
    }
  
    emit(type, arg) {
        if (this.events[type]) {
            this.events[type].forEach(listener => listener(arg));
        }
    }
}

const emitter = new EventEmitter();

emitter.on('test', message => console.log(`Test event: ${message}`));

emitter.emit('test', 'Hello World!');

2、工厂模式:工厂模式是为了在不指定确切类的情况下产生一个对象的实例。

复制代码
function CarFactory() {
  this.createCar = function(type) {
    switch(type) {
      case 'sportcars':
        return new SportCar();
      case 'suv':
        return new Suv();
      default:
        return new Car();
    }
  }
}

const factory = new CarFactory();
const car1 = factory.createCar('sportcars');
const car2 = factory.createCar('suv');

3、策略模式:策略模式定义了一系列算法,并将每一个算法封装起来,使得它们可以互相替换。

复制代码
let validator = {
    types: {},

    validate: function(value, type) {
        return this.types[type].validate(value);
    },

    registerType: function(type, handler) {
        this.types[type] = handler;
    }
};

validator.registerType('isNonEmpty', {
    validate: function(value) {
        return value !== "";
    }
});

console.log(validator.validate("Hello", 'isNonEmpty')); // true
console.log(validator.validate("", 'isNonEmpty')); // false

4、单例模式:单例模式确保一个类只有一个实例,并提供全局访问点。在JavaScript中,我们通常为对象字面量创建一个单例,因为对象字面量本质上只是一个包含多个配对属性名称-值的对象。

复制代码
var Singleton = (function () {
    var instance;
 
    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();
 
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
 
console.log(instance1 === instance2); // true,确认只有一个实例

5、代理模式:在某些情况下,一个客户不想或者不能直接引用一个对象,此时代理对象可以在客户端和目标对象之间起到中介的作用。

复制代码
function networkAccess() {
   this.request = function(url) {
       return `request: ${url}`
   }
}

function NetworkProxy() {
   this.networkAccess = new networkAccess();
   this.request = function(url) {
       return this.networkAccess.request(url);
   }
}

let network = new NetworkProxy();
console.log(network.request('https://www.google.com')); // 输出 "request: https://www.google.com"

6、装饰器模式:装饰者模式能够提供比继承更有弹性的替代方案。装饰者能够对对象添加行为,它们是构建一个类,然后用那个类包装你的对象。

复制代码
function Coffee() {
  this.cost = function() {
    return 1;
  };
}

Coffee = function(coffee) {
  this.cost = function() {
    return 1 + coffee.cost();
  };
}

let coffee = new Coffee();
coffee = new Coffee(coffee);

console.log(coffee.cost()); // 输出 2
相关推荐
用户9385156350711 小时前
写了这么久 useState,你真的知道它在干什么吗?
前端·javascript
烬羽11 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
浮江雾13 小时前
Flutter第十七节-----路由管理(3)
android·开发语言·前端·javascript·flutter·入门
那些年丶ny13 小时前
颜色扩展库
前端·javascript·数据可视化
YWL13 小时前
OpenLayers + Vue 2 使用指南(01)
前端·javascript·vue.js
大爱编程♡14 小时前
Vue3+TypeScript+element-plus的文章管理项目(配后端接口)-退出及文章管理页面
前端·javascript·typescript
独立开阀者_FwtCoder14 小时前
最近做了一个健身小程序:智形健身助手,健身的佬们来提点意见
前端·javascript·github
芝士熊爱编程15 小时前
创建型模式-单例模式
java·单例模式·设计模式
森林的尽头是阳光15 小时前
tree回显问题
javascript·vue.js·elementui
weixin_BYSJ198716 小时前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php