设计模式在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
相关推荐
GISer_Jing1 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆1 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
我在北京coding3 小时前
TypeError: Cannot read properties of undefined (reading ‘queryComponents‘)
前端·javascript·vue.js
海天胜景3 小时前
vue3 获取选中的el-table行数据
javascript·vue.js·elementui
翻滚吧键盘4 小时前
vue绑定一个返回对象的计算属性
前端·javascript·vue.js
苦夏木禾4 小时前
js请求避免缓存的三种方式
开发语言·javascript·缓存
超级土豆粉4 小时前
Turndown.js: 优雅地将 HTML 转换为 Markdown
开发语言·javascript·html
乆夨(jiuze)4 小时前
记录H5内嵌到flutter App的一个问题,引发后面使用fastClick,引发后面input输入框单击无效问题。。。
前端·javascript·vue.js
小彭努力中5 小时前
141.在 Vue 3 中使用 OpenLayers Link 交互:把地图中心点 / 缩放级别 / 旋转角度实时写进 URL,并同步解析显示
前端·javascript·vue.js·交互