This article shares the specific code for using static keywords to implement singleton mode for your reference. The specific content is as follows
Singleton pattern: Only one unique instance of a certain class can be obtained
Singleton pattern, the object obtained at any time is the same object
Look at the following code:
/** * Singleton Mode* @author xiongda * @date April 15, 2018*/public class SingletonMode { private static SingletonMode single =null; public int number = 1; //Define the constructor as private private SingletonMode(){ single=this; } public static SingletonMode getInstance(){ if(single==null){ single=new SingletonMode(); } return single; }}Privately implement the constructor method so that the external effect cannot be instantiated using new, and achieve the effect that it is actually the same object at any time.
The test code is as follows:
public class Testit {public static void main(String[] args) {// TODO Auto-generated method stubSingletonMode single =SingletonMode.getInstance();System.out.println("single's number value: "+single.number);SingletonMode single2 =SingletonMode.getInstance();single2.number=100;SingletonMode single3 =SingletonMode.getInstance();System.out.println("single3's number value: "+single3.number);System.out.println(single2==single3);}}The results are as follows:
The result shows that the references of single, single2, and single3 all point to the same object
Application of singleton mode: For example, the game window can not be opened by singleton mode.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.