Answer the question
In order to leave comments, you need to log in
What is this design pattern and how successful is it?
In some applications, I used an approach in which the factory returned objects of a certain class by id. moreover, it did not return the object itself, but a reference to it. The object itself is stored in an array in the factory. Moreover, with all requests to the factory for some id, the only instance of the class that stored the data for this id was always returned.
Thus, I achieved the fact that in the entire application there is always up-to-date information in this instance. there is only one instance and everyone refers only to it.
Also in such a class, I added methods for working and changing the object.
What is this design pattern? It seems like a singleton, but it seems not.
Do you think he is successful? In my case, he showed himself well, but I could just not get into some problem areas, what do you think?
In JS it looks like this:
/// некоторый объект, который и будет предоставлять фабрика
class Obj {
constructor(id) {
this.id = id;
this.value = 0;
}
}
/// Фабрика
class Factory {
constructor () {
this.objects = {};
}
getById(id) {
if (id in this.objects)
return this.objects[id];
this.objects[id] = this.load(id);
return this.objects[id];
}
load(id) {
let obj = new Obj(id);
/* получение данных объекта */
return obj;
}
}
let factory = new Factory(); // инициализируем фабрику, она должна быть синглтоном
// использование
let a = factory.getById(123);
console.log(a.value); // 0
let b = factry.getById(123);
console.log(b.value); // 0
b.value = 10;
console.log(a.value); // 10
console.log(b.value); // 10
Answer the question
In order to leave comments, you need to log in
What is this design pattern? It seems like a singleton, but it seems not.
Links to that are called links, which always store up-to-date information. With the same success, one could write window.objects
or var objects
.
I would even do this:
var storage={add:(key,value)=>{if(typeof(storage[key]) ==='undefined')storage[key]=value;}}
storage.add(123,{value:0});
// использование
let a = storage[123];
console.log(a.value); // 0
let b = storage[123];
console.log(b.value); // 0
b.value = 10;
console.log(a.value); // 10
console.log(b.value); // 10
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question