Learn Java single-case design model, read a few better articles and some of the book information, here to do a summary for Exchange learning
The role of a single-case design model
The singleton design pattern guarantees that there is only one object for a class and everyone is using the same object (which is verified in code below).
Second, the characteristics of the single case design pattern
1, the Singleton class has and can only have one instance
2. A singleton class must create an instance of itself
3. The Singleton class must provide a way for other class objects to get the instance
Iii. steps to create a singleton class
1. Privatization of the constructor of this class
2. Create a class object in this class through new
3. Define a common method that returns the created object and the method used by other objects to get the instance
Four, two common ways and Java code
1 Public classSingledemo {2 3 Public Static voidMain (string[] args) {4 //TODO auto-generated Method Stub5 6Single2 S1 =single2.getinstance ();7Single2 s2 =single2.getinstance ();8System.out.println (S1 = =S2);9 //output True, stating that the object is the same, validating a singleton design patternTen } One A } - //a hungry man type - classSingle1 the { - PrivateSingle1 () {} - Private StaticSingle1 s =NewSingle1 (); - Public StaticSingle1 getinstance () + { - returns; + } A } at //Lazy Type - classSingle2 - { - PrivateSingle2 () {} - Private StaticSingle2 s =NULL; - Public StaticSingle2 getinstance () in { - if(s = =NULL) tos =NewSingle2 (); + returns; - } the}
Java single-Instance design pattern