【问题标题】:Javascript - Refactor a class splitting it by conceptsJavascript - 重构一个按概念拆分的类
【发布时间】:2021-03-29 06:47:00
【问题描述】:

我正在尝试重构(按概念拆分)以下类:

import myService from "./myService"

...

export default function MyService() {
  if (!isInstantiated) {
    myService.configurate(configuration);

    // Initialize Auth and Database
    this.auth = myService.auth(); // myService.auth() has to be performed after myService.configurate()
    this.database = myService.database(); // myService.database() has to be performed after myService.configurate()

    isInstantiated = true;
  }
}

MyService.prototype.methodAssociatedWithAuthConcept = function () {
  ...
};

... more mothods associated with the "Auth" concept

MyService.prototype.methodAssociatedWithDatabaseConcept = function (email, password) {
  ...
};

... more mothods associated with the "Database" concept

将来这个类会非常大,所以把它分成其他类“Auth”和“Database”是我最好的选择,但是......myService.auth()myService.database()必须在@987654324时执行@ 在 MyService 构造函数的单例中完成。

此外,我还必须能够从 MyService 类访问 Auth 类和 Database 类,在 MyService 单例中实例化它们,以便执行以下操作:

const myServiceObj = new MyService();
myServiceObj.database.someMethodAssociatedWithDatabaseConcept();

有什么想法吗?

【问题讨论】:

    标签: javascript oop refactoring


    【解决方案1】:

    听起来你需要一个工厂。

    外包您的数据库和身份验证。然后编写一个按需实现它们的工厂。您的工厂可以为每个用例创建一个新的构造函数。构造函数实际上只是调用 Object.create() 并为您做一些原型设计的普通函数。然后他们返回使用 Object.create() 创建的对象。但是您可以完全自己处理。所以在你的构造函数中添加不同的调用很容易。

    • 提供访问身份验证和数据库的工厂标准方法。
    • 按需导入您的数据库和身份验证
    • 导出具有数据库和/或身份验证所需的所有功能的新生成类

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多