This is the 24th day of my participation in the August More Text Challenge

Speaking of singleton patterns, this is a classic of the classic design patterns in GOF 23. Most developers can implement two or three, and this article looks at all of them, along with the pros and cons of each.

A concept,

The singleton pattern is one of the simplest design patterns in Java. This type of design pattern is a creation pattern because it provides one of the best ways to create objects.

This pattern involves a single class that is responsible for creating one object while ensuring that only one object is created. This class provides a way to access the only object it can directly access without instantiating objects of that class.

Singleton pattern is widely used in practical development, such as in J2EE standard, ServletContext, ServletContextConfig, etc. And ApplicationContext in the Spring framework that we use; There are also connection pools that we use in a database connection framework that are singletons.

Singletons can be implemented in various ways, including:

  • The hungry type
  • LanHanShi
  • Double check lock type
  • Registration type (EnumImplementation)
  • ThreadLocalThread the singleton

Hungry

A henchman singleton is initialized immediately when the class is loaded and a singleton object is created. Absolute thread-safety, instantiated before threads exist, can’t have access security issues.

The implementation is as follows:

public class SingletonInHungry { private static final SingletonInHungry INSTANCE = new SingletonInHungry(); private SingletonInHungry(){ } public static SingletonInHungry getInstance(){ return INSTANCE; }}Copy the code

We can see from the code implementation, the advantages of hanhantype singleton include no lock, high execution efficiency. The disadvantage is also quite obvious, the class load is initialized, whether you use it or not, are standing space, waste of memory, may not be used for a long time, occupy the manger.

In addition, there is another implementation of hanky-hanky, as shown below, which utilizes the mechanism of static code blocks.

public class SingletonInAnotherHungry { private static final SingletonInAnotherHungry INSTANCE; static { INSTANCE = new SingletonInAnotherHungry(); } private SingletonInAnotherHungry(){} public static SingletonInAnotherHungry getInstance(){ return INSTANCE; }}Copy the code

Both implementations are easy to understand, and hanky-hanky is suitable for cases with fewer singletons.


Didn’t see enough, please jump to the next article design pattern | challenge singleton pattern (2)