JAVA design patterns-Singleton and singleton
Reprinted please indicate the source: http://blog.csdn.net/l1028386804/article/details/45441169
I,Overview
Ensure that a class has only one instance and provides a global access point to it.
II,
Applicability
1. When the class can only have one instance and the customer can access it from a well-known access point.
2. When this unique instance should be extensible through subclass, and the customer should be able to use an extended instance without changing the code.
III,
Participants
Singleton defines an Instance operation that allows the customer to access its unique Instance. An Instance is a class operation. It may be responsible for creating its own unique instance.
Iv. Category chart
V. Example
Singleton
Package com. lyz. design. singleton;/*** create a Singleton object class * @ author liuyazhuang **/public class Singleton {/*** declare a static Singleton class variable */private static singlesing ton; /*** privatize the constructor */private Singleton () {}/ *** create a Singleton object * @ return */public static Singleton getInstance () {if (sing = null) {synchronized (Singleton. class) {if (sing = null) {sing = new Singleton () ;}} return sing ;}}
Test
Package com. lyz. design. singleton;/*** Test class * @ author liuyazhuang **/public class Test {public static void main (String [] args) {Singleton sing = Singleton. getInstance (); Singleton sing2 = Singleton. getInstance (); System. out. println (sing); System. out. println (sing2 );}}
Result
com.lyz.design.singleton.Singleton@11f46b16com.lyz.design.singleton.Singleton@11f46b16