Reprint Please specify Source: http://blog.csdn.net/l1028386804/article/details/45441169
One
Overview
Ensure that a class has only one instance and provides a global access point to access it.
Two
Applicability
1. When a class can have only one instance and the customer can access it from a well-known access point.
2. When this unique instance should be extensible by subclasses, and the customer should be able to use an extended instance without changing the code.
Three
participants
Singleton defines a instance operation that allows a client to access its only instance. Instance is a class operation. may be responsible for creating its own unique instance.
Four, class diagram
V. Examples
Singleton
Package com.lyz.design.singleton;/** * Class for creating singleton objects * @author Liuyazhuang * */public class Singleton { /** * declares a static sin Gleton class Variable */ private static Singleton sing; /** * Construction Method Privatization * * Private Singleton () {} /** * Create Singleton * @return * /public static Singleton getinstance () { if (sing = = null) { synchronized (singleton.class) {if (sing = = null) {sing = new single ton (); }}} return sing;} }
Test
Package com.lyz.design.singleton;/** * Testing class * @author Liuyazhuang * */public class Test {public static void main (Strin G[] args) { Singleton sing = Singleton.getinstance (); Singleton sing2 = Singleton.getinstance (); System.out.println (sing); System.out.println (sing2); }}
Result
[Email protected] [Email protected]
On the Java design pattern--Singleton mode (Singleton)