前端常用设计模式学习之单例模式-一分钟快速理解-单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供访问该实例的全局访问点。

前端常用设计模式学习之单例模式

单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供访问该实例的全局访问点。

单例模式常常被用于管理全局状态的情况下,例如在 Vue 或 React
应用程序中管理全局应用程序状态的情况下。单例模式还可以用于确保多个对象不会意外地相互干扰,并通过减少内存占用来提高应用程序的性能。

在前端开发中,单例模式通常有以下几种实现方式:

1.简单的单例实现

class Singleton {
    
    
  constructor() {
    
    
    if (!Singleton.instance) {
    
    
      Singleton.instance = this;
    }

    return Singleton.instance;
  }

  // Your business logic methods here.
}

2.使用闭包实现单例:

const Singleton = (function () {
    
    
  let instance;

  function createInstance() {
    
    
    // Your business logic methods here.
    return {
    
    
      // ...
    };
  }

  return {
    
    
    getInstance: function () {
    
    
      if (!instance) {
    
    
        instance = createInstance();
      }

      return instance;
    },
  };
})();

// Usage:
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // Output: true

3.依赖注入实现单例:

class SingletonService {
    
    
  constructor() {
    
    
    this.data = [];
  }

  addData(data) {
    
    
    this.data.push(data);
  }

  // Your business logic methods here.
}

class MyApp {
    
    
  constructor(Service) {
    
    
    this.service = Service;
  }

  useService() {
    
    
    this.service.addData("Some data");
  }
}

// Usage:
const service = new SingletonService();
const app1 = new MyApp(service);
const app2 = new MyApp(service);

app1.useService();
console.log(service.data); // Output: ["Some data"]

app2.useService();
console.log(service.data); // Output: ["Some data", "Some data"]

总结:

无论使用哪种实现方式,单例模式都带来了很多好处。例如,它可以在应用程序中减少重复的操作,在处理全局数据时更方便,并提供了有效的性能优化。

猜你喜欢

转载自blog.csdn.net/qq_61950936/article/details/130170521
今日推荐