1 Introduction to the single-case model
the Singleton pattern ensures that there is only one instance of a class, and it instantiates itself and provides this instance to the system as a whole.
There are three key points to a singleton pattern:
1. a class can have only one instance.
2. It must create this instance on its own.
3. It must provide this instance to the system as a whole.
The singleton model is divided into two main types: a hungry man-type single-case model and lazy-type single-case model
1.1 A Hungry man single-case mode:
a hungry man single-case mode is Java The simplest single-instance mode of language implementation, UML The figure is as follows:
Figure 1.1
As you can see, it itself instantiates itself.
1.2 A Hungry man single-instance mode implementation (build a singleton package, all programs are placed under the package):
(1) Build a class that requires a singleton (Eagersingleton Java).
Package Singleton;public class Eagersingleton {private final static Eagersingleton instance = new Eagersingleton (); Private Eagersingleton () {}//static factory method public static Eagersingleton
As can be seen from the code, when this class is loaded, the static variable instance is initialized, when the private constructor method of the class is called, and the unique instance of the class is created.
Another feature is that the construction method is private, so the external cannot invoke its constructor to create an instance, but because the constructor method is private, the class cannot be inherited.
(2) write the test Class (Testeagersingleton.java).
Package Singleton;public class Testeagersingleton {public static void main (string[] args) {//TODO auto-Generate method stub 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:
[Email protected]
[Email protected]
[Email protected]
As you can see from the results, no matter how many times you create, it's the only instance.
(3) Finally, let's look at the UML diagram.
Figure 1.2
Author:vicky
Introduction: Educators
Sign : Nevermore, future
A simple analysis of Java design pattern (a)