返回

js常见的设计模式有哪些:JavaScript常见设计模式解析与实战应用

来源:网络   作者:   日期:2025-11-15 07:44:50  

JavaScript作为一门灵活且强大的编程语言,其设计模式的应用在现代前端开发中无处不在,设计模式是解决特定问题的可复用代码设计,它们帮助开发者编写更清晰、可维护的代码,本文将深入解析JavaScript中最常见的设计模式,包括其核心思想、实现方式及典型应用场景。


单例模式(Singleton Pattern)

核心思想
确保一个类只有一个实例,并提供一个全局访问点。

实现方式
通过闭包和立即执行函数表达式(IIFE)实现:

const Singleton = (function() {
    let instance;
    function createInstance() {
        const obj = new Object({name: 'Singleton Instance'});
        return obj;
    }
    return {
        getInstance: function() {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

应用场景

  • 需要频繁创建和销毁对象的场景(如数据库连接池)
  • 需要全局共享状态的场景(如配置管理)

工厂模式(Factory Pattern)

核心思想
根据输入参数的不同,返回不同类型的对象。

实现方式
通过一个函数根据条件返回不同类型的对象:

class UserFactory {
    static createUser(type) {
        switch(type) {
            case 'admin':
                return new Admin();
            case 'guest':
                return new Guest();
            default:
                throw new Error('Invalid user type');
        }
    }
}
class Admin {}
class Guest {}

应用场景

  • 对象创建逻辑复杂时
  • 需要隐藏具体对象创建细节时

观察者模式(Observer Pattern)

核心思想
定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖者会收到通知并自动更新。

实现方式
通过发布-订阅模式实现:

class Subject {
    constructor() {
        this.observers = [];
    }
    subscribe(fn) {
        this.observers.push(fn);
    }
    unsubscribe(fn) {
        this.observers = this.observers.filter(obs => obs !== fn);
    }
    notify(data) {
        this.observers.forEach(fn => fn(data));
    }
}
// 使用示例
const subject = new Subject();
subject.subscribe((data) => console.log(`Observer 1: ${data}`));
subject.subscribe((data) => console.log(`Observer 2: ${data}`));
subject.notify('Hello Observers!');

应用场景

js常见的设计模式有哪些:JavaScript常见设计模式解析与实战应用

  • 实时数据更新(如股票价格)
  • 事件处理系统
  • 状态同步场景

原型模式(Prototype Pattern)

核心思想
通过共享原型对象来实现对象间的属性复用。

实现方式
利用JavaScript的原型链特性:

const PersonPrototype = {
    init(name, age) {
        this.name = name;
        this.age = age;
        return this;
    },
    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
};
function Person(name, age) {
    Object.setPrototypeOf(this, PersonPrototype);
    this.init(name, age);
}
const alice = new Person('Alice', 30);
alice.greet(); // Hello, my name is Alice

应用场景

  • 创建大量相似对象时
  • 需要深拷贝复杂对象时

策略模式(Strategy Pattern)

核心思想
将算法封装在独立的策略类中,使它们可以互换。

实现方式
通过对象字面量实现不同算法:

const strategies = {
    add(a, b) {
        return a + b;
    },
    subtract(a, b) {
        return a - b;
    }
};
class Calculator {
    constructor(strategy = 'add') {
        this.strategy = strategies[strategy];
    }
    execute(a, b) {
        return this.strategy(a, b);
    }
}
const calculator = new Calculator('subtract');
console.log(calculator.execute(10, 5)); // 5

应用场景

js常见的设计模式有哪些:JavaScript常见设计模式解析与实战应用

  • 多种算法选择(如排序算法)
  • 需要动态改变行为时

装饰者模式(Decorator Pattern)

核心思想
动态地给对象添加功能,而不修改原对象。

实现方式
通过函数组合实现:

function original() {
    return 'Original';
}
function decorator1(func) {
    return function() {
        console.log('Decorator 1');
        return func() + ' with Decorator 1';
    };
}
function decorator2(func) {
    return function() {
        console.log('Decorator 2');
        return func() + ' with Decorator 2';
    };
}
const decorated = decorator2(decorator1(original));
console.log(decorated()); // Decorator 2 -> Decorator 1 -> Original with Decorator 1 with Decorator 2

应用场景

  • 需要动态扩展对象功能时
  • 需要避免继承带来的复杂性时

命令模式(Command Pattern)

核心思想
将请求封装为对象,使系统可支持请求的排队、记录、撤销等操作。

实现方式
通过命令对象封装请求:

class Light {
    turnOn() {
        console.log('Light is ON');
    }
    turnOff() {
        console.log('Light is OFF');
    }
}
class Command {
    constructor(light) {
        this.light = light;
    }
    execute() {
        throw new Error('Method not implemented');
    }
}
class TurnOnCommand extends Command {
    execute() {
        this.light.turnOn();
    }
}
class TurnOffCommand extends Command {
    execute() {
        this.light.turnOff();
    }
}
classInvoker {
    constructor() {
        this.commands = [];
    }
    addCommand(command) {
        this.commands.push(command);
    }
    executeCommands() {
        this.commands.forEach(cmd => cmd.execute());
    }
}
// 使用示例
const light = new Light();
const turnOn = new TurnOnCommand(light);
const turnOff = new TurnOffCommand(light);
const invoker = new Invoker();
invoker.addCommand(turnOn);
invoker.addCommand(turnOff);
invoker.executeCommands();

应用场景

  • 实现宏命令(组合多个命令)
  • 实现撤销/重做功能

设计模式是JavaScript开发中的重要工具,它们帮助开发者解决常见问题,提高代码质量,设计模式并非万能的,关键在于理解其背后的思想,并在合适的场景中应用,希望本文能帮助你更好地掌握JavaScript设计模式,提升开发效率和代码质量。

分类:编程
责任编辑:今题网
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。

文章已关闭评论!