【发布时间】:2021-03-30 06:45:01
【问题描述】:
我有一堂课,它变得非常长。我已经确定了多个不同的概念,它们共同为我的课程赋予了意义。
“MyService”类由:“auth”、“storage”、“database”组成, ... 概念。
我认为(也许我错了)在多个文件中定义类“MyService”将是一个很好的重构。比如:
MyService/MyService.js 从“./myService”导入我的服务;
export default function MyService() {
if(!isInitialized) {
myService.initializeApp(config);
// Only after doing myService.initializeApp(config);
this.auth = myService.auth();
this.storage = myService.storage();
this.database = myService.database();
isInitialized = true;
}
}
MyService/Auth.js
Add auth methods to MyService class prototype
MyService/Storage.js
Add storage methods to MyService class prototype
...
我该怎么做?这种技术有名字/存在吗?这是重构我的课程的好方法吗?如果是,为什么?如果不是,那为什么?
谢谢。
更新
也许,将类拆分为更小的类是最好的主意,但我不知道如何使它像访问 myService 功能一样工作, 这一行
myService.initializeApp(config);
之前必须在单例中执行过。
基于解决方案的示例
/* Simulate myService CLI SDK */
function myService() {}
myService.key = undefined;
myService.initializeApp = function (key) {
this.key = key;
}
myService.auth = function () {
if(!this.key) {
throw new Error("Please, initialize app");
}
console.log(`You have access to all auth methods! Key: ${this.key}`);
}
myService.storage = function () {
if(!this.key) {
throw new Error("Please, initialize app")
}
console.log(`You have access to all storage methods! Key: ${this.key}`);
}
/* Classes that compose the main class */
function Auth() {
this.auth = myService.auth();
}
Auth.prototype.login = function (username, password) {
console.log("Login!");
}
function Storage() {
this.storage = myService.storage();
}
Storage.prototype.uploadFile = function (file, path) {
console.log("Uploading file!")
}
/* Main class */
let isInitialized = false;
function Firebase() {
if(!isInitialized) { // Singleton
myService.initializeApp("raul");
this.auth = new Auth(); // Composition
this.storage = new Storage(); // Composition
isInitialized = true;
}
}
const f = new Firebase();
f.auth.login();
f.storage.uploadFile();
【问题讨论】:
标签: javascript oop refactoring ecmascript-5