设计模式在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
相关推荐
ZC跨境爬虫14 小时前
跟着MDN学HTML_day_48:(Node接口)
前端·javascript·ui·html·音视频
kyriewen17 小时前
半夜三点线上崩了,AI替我背了锅——用AI排错,五分钟定位三年老bug
前端·javascript·ai编程
AI_paid_community18 小时前
98.5k Star!GitHub官方开源的这个工具,正在把"vibe coding"扫进历史的垃圾桶
javascript·claude
AI_paid_community19 小时前
用 Claude Code 写了一年代码,装了这 18 个 Skills 之后,我才知道自己一直在"氛围编程"
javascript·面试
江米小枣tonylua19 小时前
从红绿灯到方向盘:TDD 在 AI 时代的新角色
前端·设计模式·ai编程
隔壁老王111119 小时前
浅谈JavaScript内存管理
javascript
吹牛不交税19 小时前
tree-transfer-vue3 前端插件安装问题解决(--legacy-peer-deps)(其他插件可考虑)适用
前端·javascript·vue.js
nnsix19 小时前
设计模式 - 工厂模式 笔记
笔记·设计模式
Appoint_x19 小时前
设计稿自己会说话:我用 Claude 给 Figma 做了个 AI 上下文插件
前端·javascript