Unlike C, the static in the definition of a Java class simply means that it is a regular class like any other class, but it is simply declared inside another class to organize the code. In other words, there is no behavioral difference between the following two methods of declaring *:
but)
class SomeOtherClass { static class Me {
b)
class Me {
Class definitions are loaded into memory when the class is used for the first time, and this is true for the static and non-static classes. There is no difference in how memory will be used. In older JVMs, objects were always stored on the heap. Modern JVMs allocate objects on the stack whenever possible and useful, but this optimization is transparent to the encoder (it is impossible to influence this behavior using code), and the use of the static does not affect this behavior.
Now, back to the original question, as we saw, we really cannot compare static classes and Singleton in Java, since they are completely different concepts in Java (I'm also not sure how static classes would compare to Singleton, but I will focus on Java in this answer). The static in Java is overloaded and has many meanings, so it can be confusing.
Is Singleton automatically an “anti-pattern”? I do not think so. Singleton's abuse is that, but the Singleton pattern itself can have many good uses. It just happens that a lot of abuse. If you have a legitimate reason to use the Singleton template, there is nothing wrong with using it.
* Note. Why write
static at all, you may ask. It turns out that the “non-static” nested classes have their own somewhat complicated memory management functions, and its use is usually discouraged unless you have a good reason (see Other questions for more information).
class SomeOtherClass { Stuff stuff; class Me { void method(){
Enno shioji
source share