In program development, sometimes we only need an object, such as Log object, tool class, how to ensure that there is only one object in the entire application? This will use a singleton pattern, which can be seen by name, which guarantees that there is only one instance of the entire application. Singleton, single case, is a single instance. Now let's look at how to implement a singleton pattern in Java code.
First use Eclipse to create a Java project, and then in the SRC directory, a new singleton class, which is used to create a single object, and then a new test class for testing, it is best to specify a package name
We all know that the constructor of the class is called when the object is created, but each time a call is made, a new object is created, which does not match our creation of a single object. What do we do then? First, you cannot let the outside call the constructor of the class, that is, to privatize the constructor function
// privatization of constructor functions Private Singleton () { }
After the constructor is privatized, we cannot create objects outside, but another problem has been raised, and the object that we need is not created, it is necessary to provide a way to create an object. We create an object in this class and then provide a way to expose it because we can call the constructor in this class.
// Unique instance of the object Private Static New Singleton (); // provides a way to get an instance Public Static Singleton getinstance () { return instance; }
Then we can get out of the class name and test it in the test class.
Public class Test { publicstaticvoid main (string[] args) { = Singleton.getinstance (); = singleton.getinstance (); = = s2); // true }}
The two objects created S1, S2 equal, prove that they are the same object. The creation of the above singleton pattern is called ' a Hungry man ', because when the class is loaded, this unique object is created.
Now let's consider another pattern of creating singleton objects, called ' lazy ', that is, when we declare private properties, we do not create objects, only to create singleton objects when invoking instances.
Public classSingleton {//privatization of constructor functions PrivateSingleton () {}//only one object is declared, and no assignment is made Private StaticSingleton instance; //provides a way to get an instance Public StaticSingleton getinstance () {if(Instance = =NULL) {//when the first call is made, the singleton object is createdInstance =NewSingleton (); } returninstance; }}
Java design pattern------Singleton mode