Java Design Patterns: Singleton

Singleton

It recommends ways: Enumeration way to achieve a singleton

Singleton pattern defined

Singleton is in the program run only instantiated once, to create a globally unique object, a bit like Java's static variables, but Singleton pattern is superior to static variables, static variables JVM will be loaded when the program starts, if not in use, will cause a lot of waste of resources, singleton lazy loading can be achieved, you can only go to create an instance when using instance. Development tools, libraries Many tools are applied singleton mode, the proportion of the thread pool, cache, logs and other objects, they only need to create an object, if you create multiple instances, may lead to unpredictable problems, such as waste of resources, deal with inconsistent results and other issues.

Seven kinds of implementations

  1. Lazy mode, thread safe
  2. Lazy mode, thread-safe
  3. Starving mode
  4. Hungry man model variants
  5. Static inner classes mode
  6. Mode enumeration class
  7. Double-check lock mode

When the class is loaded, it will load the class inside a static variable (ie static variables allocated memory space), so that when the class is instantiated, you can directly use, speed.

Class at each instantiation, the constructor call corresponding to complete the initialization of the class member variables in a non-static variable, allocating memory space corresponding

Why enumeration class to implement Singleton pattern more and more popular?

reference:

https://mp.weixin.qq.com/s/aGMz1u0Oh4ZHTDBFvgq0lg

Guess you like

Origin www.cnblogs.com/shengulong/p/11809611.html