Elements of the Singleton pattern:
1. private static Instance Object
2. Private constructors (guaranteed to be outside of this class, cannot create object instances by means of new)
3. Public, static, methods to access the instance object
1. A Hungry man mode:
public class Singleton1 { private static Singleton1 singleton = new Singleton1 (); Private Singleton1 () { } public static Singleton1 getinstance () { return singleton;
Pros: Thread safety, absolute Singleton.Cons: When a multi-instance or other static method is used, it is loaded at startup without using it, wasting memory.
2. Lazy Mode:
public class Singleton2 { private static Singleton2 singleton; Private Singleton2 () { } public static synchronized Singleton2 getinstance () { if (singleton = = null) Singleton = new Singleton2 (); return singleton; } }
Pros: Save memory when no time is used to load.
Cons: Thread is unsafe, prevents deserialization and reflection from generating new instances.
Single-instance mode in multithreaded mode (simple difference between hunger and a Hungry man mode)