The Singleton mode can be used in the following two forms:
Singleton Mode features: Solves the uniqueness of a class in the memory, and the class has only one object.
Steps for writing the singleton mode:
1. Private modifier Constructor
2. In the member position of this class, the new class Object
3. Provide a static method to return the objects of this class.
A: A tough guy
Package demo01;/*** single-instance Design Pattern tough style * @ author Administrator **/public class SingleDesignModel1 {// private constructor private SingleDesignModel1 () {}// in the position of your member variables, new private static final SingleDesignModel1 singleDesignModel1 = new SingleDesignModel1 (); // provides a static method, returns a public static SingleDesignModel1 getInstance () {return singleDesignModel1 ;}}
B: lazy
Package demo01;/*** example mode lazy * @ author Administrator **/public class SingleDesignModel2 {private static SingleDesignModel2 singleDesignModel2 = null; private SingleDesignModel2 () {} public static SingleDesignModel2 getInstance () {if (singleDesignModel2 = null) {singleDesignModel2 = new SingleDesignModel2 ();} return singleDesignModel2 ;}}
Operating principle of Singleton mode: