Analysis of JAVA Design Pattern Singleton pattern (1), analysis of java Design Pattern
1 Overview of Singleton Mode
The Singleton mode ensures that a class has only one instance and instantiates the instance and provides the instance to the entire system.
The Singleton mode has three key points:
1. A class can only have one instance.
2. It must create the instance on its own.
3. It must provide this instance to the entire system.
The Singleton mode can be divided into two types: the hungry Singleton mode and the lazy Singleton mode.
1.1 hunger Singleton mode:
The hungry Chinese Singleton mode is the simplest Singleton Mode Implemented by java. The UML diagram is as follows:
Fig 1.1
It can be seen that it will instantiate itself.
1.2 Implementation of the hungry Chinese Singleton mode (create a Singleton package and put all programs under this package ):
(1) create a singleton class (EagerSingleton java ).
Package Singleton; public class EagerSingleton {private final static EagerSingleton instance = new EagerSingleton (); private EagerSingleton () {}// static factory method public static EagerSingleton getInstance () {return instance ;}}
The Code shows that when this class is loaded, the static variable instance is initialized, and the private constructor of the class is called, the unique instance of the class is created.
Another feature is that the constructor is private, so the external cannot call its constructor to create an instance. However, because the constructor is private, this class cannot be inherited.
(2) Compile the test class (TestEagerSingleton. java ).
Package Singleton; public class TestEagerSingleton {public static void main (String [] args) {// TODO automatically generates method stubs EagerSingleton eagersingleton1 = EagerSingleton. getInstance (); EagerSingleton eagersingleton2 = EagerSingleton. getInstance (); EagerSingleton eagersingleton3 = EagerSingleton. getInstance (); System. out. println (eagersingleton1); System. out. println (eagersingleton2); System. out. println (eagersingleton3 );}}
Output result:
Singleton. EagerSingleton @ c17164
Singleton. EagerSingleton @ c17164
Singleton. EagerSingleton @ c17164
The result shows that no matter how many times you create an instance, it is a unique instance.
(3) let's take a look at the UML diagram.
Fig 1.2
Author: Vicky
Introduction: educators
Sign: never forget the past and never forget the future