D
D
Dauren S2016-12-29 10:40:06
Design patterns
Dauren S, 2016-12-29 10:40:06

What is singleton for?

What is singleton for? It is clear that to create a single instance of a class. And what is this single instance for? What is the purpose?

Answer the question

In order to leave comments, you need to log in

11 answer(s)
A
Adamos, 2016-12-29
@Adamos

Singleton is a great indicator. If a person asks the question why he is needed, it means that this person is too lazy to even read Wikipedia.
However, there is a consolation option: this person simply has not yet written a single workable program, and it is stupidly early for him to study design patterns.

E
Evgeny Shatunov, 2016-12-29
@MarkusD

In a literal sense, a singleton is designed to simplify ownership, initialization, lifetime control, and access to elements of the program's global state. This phrase is the most important. And the most important thing is to understand it correctly.
The approach has been repeatedly denounced by the anti-pattern for the fact that "the global state of the program is evil", despite the fact that the global state continues to remain in the program even after removing all singletons from the project.
I've seen projects with more than 50 singletons and very heavy communication problems. Literally everything was pulled out into singletons indiscriminately and ignorantly. This is a vivid example of the anti-approach of applying absolutely any pattern.
It is important to understand that no design element is an anti-pattern, it only leads to problems when used ineptly.
An application that consists of exactly one UI form will have global state as that form, whether that form is styled as a singleton or not. Simply, if not, then this form has to be managed in other ways, not always more convenient than a singleton.
As an alternative to singletons, two other approaches are promoted: Registry / Service locator and Dependency injection .
By the way, all alternatives are just as actively and still undeservedly called anti-patterns. :)
Now to the examples.
- DirectX. To work with graphics, you need one instance of the IDirect3D and IDirect3DDevice interfaces. These two instances declare the global state of the program. All buffers, textures, shaders and surfaces are instantiated using these instances. It makes sense to provide access to DirectX instances via the singleton approach.
- OpenGLgood old versions. The procedural interface of OpenGL hints at the absence of the need for global state. But it was not there. To work with OpenGL, you must not only create a context, but also remember the thread in which this context is associated with the output surface. In a multithreaded environment, there can be several contexts for loading resources in parallel. In this case, you need to remember two threads and two contexts (minimum). Of course, in a singleton, this global state looks more convenient.
- Sockets . It doesn't matter what. When your application is an MMO project and you have a mountain of subsystems that constantly and separately communicate with the server, it is reasonable to arrange the network connection in the form of a singleton.
- Assets / Resources- they are different, cacheable and not, available from the network, from the hard disk, from the pre-rendering subsystem. Again, I've seen the pain and suffering of patchy resource control several times without a proper subsystem. And the resource management subsystem itself is always centralized and is best implemented on a singleton.
Sound, input, multi-threaded task pipeline... you can remember the places where singletons are clearly needed for a long time.

R
Roman Sokolov, 2016-12-30
@jimquery

It's easier, I think, to explain using an example with a database.
Let's say you have a program with several forms, each of which uses some data. If you create your own database object on each form and write / read data through it, then at one point in time the data between the forms may differ and contradict each other.
To solve this problem, you create a database instance in a single state (singletone) and use a reference to it in each form. In this case, the same data will be used on each form.

I
Ilya Karavaev, 2016-12-29
@Quieteroks

It's elementary. Initially, as a replacement for global variables. It is one and therefore all calls to it bring changes in the entire project. In one place, you created a connection to the database and then you can already use it in any part of the program without recreating the connection and passing it as a function argument each time.
In fact, it is enough to read any of its descriptions and it becomes clearer.

R
Rafael™, 2016-12-29
@maxminimus

not always and not everyone needs classes and instances,
as well as inheritance and prototyping
, it happens that one object is one functional part of your architecture, one module in one named container { }

T
trubel, 2016-12-29
@trubel

Watch the webinar on patterns on Hecklet , somewhere around 1:20 the discussion of the singleton begins, by the end of the video the results are summed up.
In short, a singleton is a replacement for a global variable to carry the application context with it, its use has certain limitations. It is better to use a dependency container for the application context.
In general, I recommend watching the video in its entirety, it clearly puts on the shelves about the patterns.

K
kahi4, 2016-01-01
@kahi4

Singleton is needed primarily to create extra hemorrhoids. At first, it seems so wonderful and wonderful, but once you bring testing into your application, big problems begin. And then it turns out that two database connections are needed for one reason or another, and the settings need to be spaced out depending on the user and some other external factors, which ultimately leads to rewriting most of the code base. In other words - before using it, you need to think carefully and see if you can do without it.
But it was invented all the same for a good purpose: to encapsulate access points to external resources - as a rule, you need one connection to the database, one point with settings and so on. And so, in order not to create a new instance every time, in order not to allocate resources, in order to be able to implement lazy loading, a pattern was developed that allows you to access the resource from anywhere in the application and not forward class instances / connection parameters / other in each function, which is often inconvenient.

P
protven, 2017-01-02
@protven

As a person who can write about five implementations of a singleton and who does not use them, I can say for sure that this is already more of an interview question than from real life. In general - sometimes you need it, but it's easier to google it.

W
WAERZ, 2016-12-30
@WAERZ

There is
And there is

public static function getInstance(){
if (self::instance === null){
 self::instance = new self();
} 
return self::instance;
}

That is, we place an object of the class in the instance variable and then get this object through getInstance, and do not create it every time. It's convenient, but you should only use it where it's worth. For example, to connect to a database.

C
cap_nemo, 2016-12-31
@cap_nemo

Sometimes there is a need for something unique...
By the "flow" of the code, we understand that entities can multiply and it becomes difficult to manage them.
Do you need multiple instances of the same application, or multiple pointless connections to the same database?
Not necessarily - and so, in most cases.
Then you need a mechanism that will ensure the uniqueness of . And, this pattern does just that. Voila!
How exactly - it already depends on the semantics of the language.
The general meaning is - you need something unique, use it.
Some guys spin metal miniatures in such cases :-)

G
Grigory Vasilkov, 2016-01-01
@gzhegow

Feel the difference between a car factory, a car and an owner company. a singleton in this case is, for example, a connection to a database, a kind of code construction available anywhere in the program. In the car example, the company itself could be a singleton to get permission from time to time when working in a factory, or just ask for the company name. The singleton is needed so as not to lose the object in the thickness of the code, but I am more and more inclined to return the object when the class is included in the assembly file. Cant that in php before version 5.6 the word array had to be written in full, so they came up with the opportunity to return a single instance of the class using statics anywhere in the program. With the same success, you can do return include new App and then pass the object as a parameter to another function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question