A
A
alpha9172017-10-26 10:03:33
Programming
alpha917, 2017-10-26 10:03:33

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

2 answer(s)
M
Maxim Fedorov, 2017-10-26
@alpha917

What is this design pattern? It seems like a singleton, but it seems not.

FlyweightFactory
It is difficult to judge because the successful use of a template depends only on the task to which it is applied. If your objects do not particularly have states, then this pattern is quite appropriate to apply, but if your objects are entities, then you should apply the Identity Map pattern

G
Griboks, 2017-10-26
@Griboks

Links to that are called links, which always store up-to-date information. With the same success, one could write window.objectsor 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 question

Ask a Question

731 491 924 answers to any question