E
E
eugenedrvnk2021-12-09 19:29:24
JavaScript
eugenedrvnk, 2021-12-09 19:29:24

Singleton or normal object?

Now I’m reading about different patterns and I didn’t understand the moment about the singleton a little.
By definition, this is a class that can only have one instance within an application.
And what in such a situation prevents you from simply creating an object that will have similar functionality and that's it? (instead of creating a class and an instance of that class)
What are the benefits of creating a class exactly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GrayHorse, 2021-12-09
@GrayHorse

And what in such a situation prevents you from simply creating an object

Because in Java, C# you can't write something like this:
export const singleton = {name: "foo"}; // Полноценный синглтон для JS

Only classes are imported and exported. It is impossible to create a global variable that will store the global state, which can then be imported in different files (classes).
Therefore, we need a class that will have a static field containing this global state.
Because there should be only one instance of the class, by whom should it be created? And it is created "automatically" - directly when the class is loaded in the static class initialization block (yes, this is also in JS), and as an additional precaution so that no one creates a second instance, the constructor is made private - inaccessible to any code that will work with this class.
What are the benefits of creating a class here?

Functionally, none.
The code will look more familiar to people familiar with Java and C#.
For the sake of formality, after all, yes, there is a difference, and it is that in the case of using a class, that object will be an instance of the singleton class, and another instance of this class cannot be created. You can even check with instanceofto make sure that it is an instance of that class that can only be in one instance, and not some other object. And if it's "just an object" - you can slip a complete "copy" without any problems by creating it using a literal notation.

B
briahas, 2021-12-12
@briahas

IMHO, why is a singleton, and not a regular object - in order for the object to be the same in different parts of your program - you need to pass it there.
Singleton, on the other hand, is enough just to create an instance of this class and the instance created earlier, at the other end of the application, will automatically be pulled up. Which will give us "by definition the only instance" as written by previous speakers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question