Answer the question
In order to leave comments, you need to log in
When to use a static class and when alone?
Some people say that using a static class where the methods are all static is bad and you should use the singleton pattern instead, but why is that? What's the difference and what do you prefer?
Answer the question
In order to leave comments, you need to log in
What's the difference and what do you prefer?
If the class is utilitarian, such as Math from Java, where all methods are essentially functions and do not change the external state, then a static one is better. As soon as the class has a state (in the form of the same static data fields), it is worth making a singleton out of it. A singleton can implement some interfaces, and it can be used like a regular object.
It is also easy to turn a singleton into a non-singleton (that is, a class with many instances), if necessary.
What interesting things have been written. Static classes in Java are needed because there are no functions in Java. In other languages, functions are grouped by namespace.
The difference between a static class and a singleton is that a static class is initialized at the start of the program, and a singleton is only initialized when it is accessed (in addition, a method can be added to the singleton to free memory from the instance).
For example, there is frequent functionality required by the user throughout the program, and you can make a static class. If the user rarely needs functionality and may need it in the middle or at the end of the program, then we choose the sington.
enum class ProgState {Init, Run, Release};
//вариант 1
bool isLastDoc = (App::state () == ProgState::Init);
App::LoadDocument ( isLastDoc );
//вариант 2
bool isLastDoc = (App::getInstance () -> state () == ProgState::Init);
App::getInstance() -> LoadLastDocument( isLastDoc );
//app.h
App& app (); //здесь можно и статик переменую, а не функцию
//app.cpp
App & app ()
{
static App app;
return app;
}
//в коде
bool isLastDoc = (app() -> state () == ProgState::Init);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question