在现代面向对象的 JavaScript 应用程序中,有没有好的设计模式可以在类实例之间共享数据?
例如,我正在构建一个带有组件的应用程序。它们是类实例。其中一些共享相同的数据。我知道您可以使用构造函数中注入的单例服务。该解决方案是在 AngularJS 框架中实现的。但是不使用单例模式还有其他解决方案吗?我正在寻找一些有关 JavaScript 应用程序架构设计的文章。
我创建了某种注射器,这可能不是最好的解决方案:
export const Injector = {
instances: {},
add<T>(Class: { new(...args: any[]): T }, ...args) {
const className = new Class().constructor.name;
const instances = args.map((item) => this.get(item));
if (!this.instances[className]) {
this.instances[className] = new Class(...instances);
}
},
get<T>(Class: { new(...args: any[]): T }): T {
const className = new Class().constructor.name;
return this.instances[className];
}
};
在面向对象编程中,您的程序是可以通过其他对象的接口与其他对象进行通信(调用其方法)的对象。
根据您的需要,您可以使用与对象的“常规”关联(将对象放入构造函数中)。
class Greetings {
hello() {
return "Hello world!"
}
}
class ForwardConsole {
constructor(greetings) {
this.greetings = greetings;
}
print() {
console.log(this.greetings.hello());
}
}
class BackwardConsole {
constructor(greetings) {
this.greetings = greetings;
}
print() {
console.log(this.greetings.hello().split("").reverse().join(""));
}
}
let greetings = new Greetings();
let fc = new ForwardConsole(greetings);
let bc = new BackwardConsole(greetings);
在代码中,我们使用标准构造函数将同一个对象封装(注入)到不同的对象中。