Design Mode-Singleton, design mode-
The Singleton mode is a common design mode.
The Singleton mode has the following features:
1. A singleton class can only have one instance.
2. The Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.
Hungry Chinese Singleton
public class Singleton { private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; }}
When a class is created, a static object has been created for the system and will not be changed in the future.
Lazy Singleton
Public class Singleton {private static Singleton instance = null;/*** lazy Mode 1 * Synchronization Method */public static synchronized Singleton getInstance () {if (instance = null) {instance = new Singleton ();} return instance;}/*** lazy Mode 2 * synchronization code block */public static Singleton getInstance () {synchronized (Singleton. class) {if (instance = null) {instance = new Singleton () ;}} return instance ;}}
Low efficiency when synchronizing code or code blocks
Double lock check
public class Singleton { private static volatile Singleton instance = null; public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}
Thread security to improve efficiency
Internal static class
public class Singleton { private static class SingletonHandler { private static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHandler.instance; }}