设计模式在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
相关推荐
cos1 小时前
Fork 主题如何更新?基于 Ink 构建主题更新 CLI 工具
前端·javascript·git
摸鱼的春哥2 小时前
AI编排实战:用 n8n + DeepSeek + Groq 打造全自动视频洗稿流水线
前端·javascript·后端
坚定学代码3 小时前
基于观察者模式的ISO C++信号槽实现
开发语言·c++·观察者模式·ai
Coder_Boy_3 小时前
基于SpringAI的在线考试系统设计总案-知识点管理模块详细设计
android·java·javascript
冴羽5 小时前
2026 年 Web 前端开发的 8 个趋势!
前端·javascript·vue.js
fengbizhe5 小时前
bootstrapTable转DataTables,并给有着tfoot的DataTables加滚动条
javascript·bootstrap
刘一说5 小时前
TypeScript 与 JavaScript:现代前端开发的双子星
javascript·ubuntu·typescript
GISer_Jing5 小时前
AI Agent 目标设定与异常处理
人工智能·设计模式·aigc
蔺太微6 小时前
组合模式(Composite Pattern)
设计模式·组合模式
EndingCoder6 小时前
类的继承和多态
linux·运维·前端·javascript·ubuntu·typescript