The singleton mode has the following characteristics:
- A singleton class can have only one instance
- A singleton class must create its own unique instance
- The Singleton class must provide this instance to all other objects
A hungry man singleton mode: Because the constructor is a private type, this class is not inheritable
public class Eagersingleton {private static final Eagersingleton m_instance=new Eagersingleton ();/* Private default constructor */private Eagersingleton () {}/* static factory method */public static Eagersingleton getinstance () {return m_instance;}}
It can be seen that when this class is loaded, the static variable m_instance is initialized and the private constructor is called. At this point, the only instance of the Singleton class is created.
Lazy Singleton mode: Because the constructor is a private type, this class is not inheritable
public class Lazysingleton {private static Lazysingleton m_instance=null;/* privately default constructor */private Lazysingleton () {}/* Static Factory method */synchronized public static Lazysingleton getinstance () {if (m_instance==null) {m_instance=new Lazysingleton ();} return m_instance;}}
The necessary condition for using singleton mode is that a system requires that only one instance of a class should use Singleton mode. If a class allows several different instances to coexist, then there is no need to use singleton mode.
Singleton mode (singleton)