How do the objects created following Singleton work?

Asked

Viewed 277 times

11

I would like to understand how objects created work by following the Pattern Singleton javascript design.

My main doubts refer to the methods and attributes of this object, where and how to create them and where and how to access them.

I read some articles even in English but I did not understand very well how to use Singleton correctly.

As an example I have this code:

Source: Dofactory - Singleton

var Singleton = (function () {
    var instance;

    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

function run() {

    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();

    alert("Same instance? " + (instance1 === instance2)); //retorna true 
}

Objects are being instantiated in Function run, my doubt on that would be, if I want to add a method stop and an attribute status to know if this object is in run or stop, how should I do this by following the Pattern design singleton?

Reference:
A Beginner’s Guide to Design Patterns
Javascript Design Patterns: Singleton

  • 2

    Related: http://answall.com/questions/40603/singleton-em-javascript

  • Hello, @Rodrigo. Your doubts are not clear enough. You said they refer to such things, but what exactly are these doubts? Perhaps with examples it becomes clearer.

  • @Pablo added an example and tried to explain my doubt better, see if it’s better now

  • "The objects are being instantiated" the object, not "os" - the idea of Singleton is just that there is only one instance. This example uses Lazy instantiation, but could also not use, creating the object directly. Anyway, it is the function createInstance that you have to change, to modify your object Singleton. Instead of new Object("I am the instance"), you put whatever you want your object to be. And the pattern ensures that it will be the same object whenever you use getInstance. P.S. didn’t understand this part: "know if this object is in run or stop"

  • @mgibsonbr would only be the value of the status attribute, I think I’m beginning to understand...

4 answers

4


Maybe start by looking at memory pointers.

View this situation using NEW

var a = new Object('Some Object A');
var b = new Object('Some Object B');

In this code we have two objects created in two different variables. In the memory of your machine, it looks like this:

Código                   Memória
var a ---------------->  Posição 0000
var b ---------------->  Posição 0001

Dare it be, two copies are created.

If I do this:

var c = b;

In that case, c === b, because:

Código                   Memória
var a ---------------->  Posição 0000
var b ---------------->  Posição 0001
var c ---------------->  Posição 0001

Note that both b and c point to the same memory area, that is, the same object.

That’s a basic of how it works, summed up. Now look at your example:

getInstance: function () {
  if (!instance) {
    instance = createInstance();
  }
  return instance;
}

Here you’re making that up instance does not exist, so creates an instance. So each time you call getInstance, the first time he creates with NEW and the others just returns what was already created the first time.

Putting this in the examples I quoted:

var a = Singleton.getInstance();
var b = Singleton.getInstance();
var c = Singleton.getInstance();


Código                   Memória
var a ---------------->  Posição 0000
var b ---------------->  Posição 0000
var c ---------------->  Posição 0000

In short, this is because only once is created and in the other, only one reference to the Singleton instance is returned.

I hope the text helped!!!

  • Congratulations, I’m looking at the Maximillian course from Understanding Typescript - 2020 Edition, and I find it sensational, and I’m in Singletons & Private Constructors, and I’d like to know if this helps us not to use too much memory, of course, in small cases it doesn’t make a difference.

0

In his example, Object would be the object you want to make a Singleton. Simply replace (since you have defined your object) and if you only use Singleton, you will always have only one copy of the object.

You must create your methods run and stop within the definition of that object its.

For a review of how this is done, take a look here: How prototypes work in Javascript?

0

One way to visualize is as follows.

Imagine you have a database connection class, and you don’t want to create a new object in memory every time you need to access the database, so you use Singleton.

This will ensure that multiple objects are created to do a common thing in various parts of the project.

-2

const miSingleton = (function () {
// instancia guarda a referencia singleton
let instancia;

function init () {

    function metodoPrivado () {
        console.log('Eu sou privado');
    };

    let varPrivada = 'Sou uma variable privada';
    let numeroRandomicoPrivado = Math.random();

    return {
        metodoPublico: function (params) {
            console.log('Sou um metodo público');
        },
        propiedadePublica:'Sou uma propiedade publica',
        obterNumeroRandomico: function () {
            return numeroRandomicoPrivado;
        }
    };
};

return {
    // Obtenha a instancia singleton se nao existe ou crie uma
    obterIntancia: function () {
        if (!instancia) {
            instancia = init();
        }
        return instancia;
    }
};

})(); const singleA = miSingleton.obter Tancia(); const singleB = miSingleton.obtenIntancia(); console.log(singleA.obtain console.log(singleA.obtain console.log(singleB.get());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.