The singleton mode guarantees that the class in the system has only one instance. The main points of the singleton pattern are three; one is that a class can have only one instance, and the other is that it must create this instance on its own, and thirdly, it must provide this instance to the whole system on its own. Singleton mode can be divided into two modes: a hungry man mode, lazy mode.
1. A Hungry man mode
Public classEhansingleton {//define private parameterless constructs to prevent class instances from being fetched by new method PrivateEhansingleton () {}//Create a unique instance of the class, using private, static adornments to ensure that the class loads and creates instances, so called a hungry man mode Private StaticEhansingleton Ehansingleton =NewEhansingleton (); //provides methods for getting an instance Public StaticEhansingleton getinstance () {returnEhansingleton; }}
Test
Public class Test { publicstaticvoid main (string[] args) { = Ehansingleton.getinstance (); = ehansingleton.getinstance (); = = E2); // true, the result shows that E1, E2 are the same instance }}
2. Lazy mode
Public classLanhansingleton {//define private parameterless constructs to prevent class instances from being fetched by new method PrivateLanhansingleton () {}//declaring a unique instance of a class Private StaticLanhansingleton Lanhansingleton; //provides a method for getting an instance, which is called lazy mode when the instance is created the first time it is acquired Public StaticLanhansingleton getinstance () {if(Lanhansingleton = =NULL) Lanhansingleton =NewLanhansingleton (); returnLanhansingleton; }}
Test
Public class Test { publicstaticvoid main (string[] args) { = Lanhansingleton.getinstance (); = lanhansingleton.getinstance (); = = L2); // true, the result shows that L1, L2 are the same instance }}
3, a hungry man mode, lazy mode difference
1) The A Hungry man mode is created when the class is loaded, so the class is loaded slowly, but the runtime gets faster. Lazy mode is the opposite.
2) A hungry man mode is thread-safe, and lazy mode is non-thread safe.
Java design pattern (i) Singleton mode