Singleton mode: used to ensure that a class has only one instance during a certain degree of Operation
Advantage: to save resources as much as possible
Application scenarios
--------------------
The Singleton mode is implemented by modifying the access permissions of the constructor.
For example
Package com. lixiyu; public class TestExample1 {public static void main (String [] args) {System. out. println ("create SHENMA 1 object:"); SHENMA shenma1 = SHENMA. getInstance (); // create object shenma1.getName (); // output name System. out. println ("create SHENMA 2 object:"); SHENMA shenma2 = SHENMA. getInstance (); // create object shenma2.getName (); // output name System. out. println ("create SHENMA 3 object:"); SHENMA shenma3 = SHENMA. getInstance (); // create object shenma3.getName (); // output name }}
Create a shenma class to describe it.
Package com. lixiyu; public class SHENMA {private static SHENMA shenma = null; // declare a reference to a class SHENMA private SHENMA () {// privatize the constructor} public static SHENMA getInstance () {if (shenma = null) {shenma = new SHENMA ();} return shenma;} public void getName () {System. out. println ("this is a good thing ");}}
You only need to create a new instance once to solve the problem.
public static SHENMA getInstance(){ if(shenma==null){ shenma=new SHENMA(); } return shenma;}
The Singleton mode also has many writing methods, which are just one of them. We will record them later in our studies.
This article is from the "ToBeContinued" blog, please be sure to keep this source http://leexy.blog.51cto.com/4136883/1304452