登录
首页 >  文章 >  前端

单例与工厂模式设计解析

时间:2026-01-06 23:32:53 188浏览 收藏

哈喽!今天心血来潮给大家带来了《JS设计模式:单例与工厂实现解析》,想必大家应该对文章都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习文章,千万别错过这篇文章~希望能帮助到你!

单例模式确保类仅有一个实例并提供全局访问,常用于共享资源管理;工厂模式则通过封装对象创建过程实现解耦,便于扩展不同类型对象的生成;二者结合可提升代码的可维护性与灵活性。

JS设计模式:单例模式与工厂模式实现

单例模式和工厂模式是JavaScript中常用的两种设计模式,它们分别解决对象创建过程中的不同问题。单例模式确保一个类只有一个实例,并提供全局访问点;工厂模式则封装对象的创建过程,使代码更灵活、可扩展。

单例模式:保证唯一实例

单例模式的核心是:无论调用多少次构造函数,都只返回同一个实例。这在需要共享资源时非常有用,比如全局配置、日志管理器或数据库连接池。

实现方式通常使用闭包或ES6的模块机制来控制实例的创建与访问。

基本实现(闭包 + 静态变量):

class Singleton {
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    this.data = 'I am the only instance';
    Singleton.instance = this;
    return this;
  }

  getData() {
    return this.data;
  }
}

// 使用示例
const instance1 = new Singleton();
const instance2 = new Singleton();

console.log(instance1 === instance2); // true

上面的实现通过检查 Singleton.instance 是否已存在,决定是否返回已有实例。这种方式简单有效,但依赖于手动维护静态属性。

更安全的实现(利用闭包隐藏实例):

const createSingleton = (function () {
  let instance = null;

  return function () {
    if (!instance) {
      instance = {
        data: 'I am unique',
        getData() {
          return this.data;
        }
      };
    }
    return instance;
  };
})();

// 使用
const s1 = createSingleton();
const s2 = createSingleton();
console.log(s1 === s2); // true

这种写法将实例私有化,避免外部直接修改,增强了封装性。

工厂模式:解耦对象创建

工厂模式用于创建对象,而无需指定具体类。它把对象的创建逻辑集中在一个“工厂函数”或“工厂类”中,客户端只需传入参数即可获得所需对象。

适用于需要根据条件生成不同类型对象的场景,比如UI组件生成、消息类型处理等。

简单工厂模式(函数形式):

class Button {
  render() { throw new Error('Must implement render'); }
}

class WindowsButton extends Button {
  render() {
    return '<button class="windows">Windows Button</button>';
  }
}

class WebButton extends Button {
  render() {
    return '<button class="web">Web Button</button>';
  }
}

// 工厂函数
function ButtonFactory(type) {
  switch (type) {
    case 'windows':
      return new WindowsButton();
    case 'web':
      return new WebButton();
    default:
      throw new Error(`Unknown button type: ${type}`);
  }
}

// 使用
const btn1 = ButtonFactory('windows');
const btn2 = ButtonFactory('web');

console.log(btn1.render()); // Windows Button
console.log(btn2.render()); // Web Button

通过工厂函数,调用方不需要知道具体的子类,只需要传入类型字符串就能得到正确的对象。

工厂类模式(更结构化):

class ButtonFactory {
  static create(type) {
    if (type === 'windows') {
      return new WindowsButton();
    } else if (type === 'web') {
      return new WebButton();
    } else {
      throw new Error('Unsupported type');
    }
  }
}

// 使用
const button = ButtonFactory.create('web');
console.log(button.render());

工厂类更适合复杂系统,便于扩展和维护。

结合使用场景

实际开发中,可以将单例模式用于工厂本身,确保工厂也只有一个实例:

const ButtonFactorySingleton = (function () {
  let instance = null;

  class Factory {
    create(type) {
      // 同上工厂逻辑
      if (type === 'windows') return new WindowsButton();
      if (type === 'web') return new WebButton();
      throw new Error('Invalid type');
    }
  }

  return function () {
    if (!instance) {
      instance = new Factory();
    }
    return instance;
  };
})();

// 全局唯一的工厂实例
const factory = ButtonFactorySingleton();
const another = ButtonFactorySingleton();
console.log(factory === another); // true

这样既保证了对象创建的灵活性,又控制了资源使用。

基本上就这些。单例模式关注“唯一性”,工厂模式关注“创建解耦”,两者结合能提升代码的可维护性和可扩展性。

到这里,我们也就讲完了《单例与工厂模式设计解析》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于单例模式,JS设计模式的知识点!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>