---restore content starts---
Design Patterns: The most effective way to solve a class of problems there are 23 design patterns in Java. Learn one of these today: a singleton design pattern: Solving a class in memory only one object exists
Want to guarantee that the object is unique.
1. To prevent other programs from creating such objects too much, first prevent other programs from establishing such objects
2. Also in order for other programs to have access to the class object, in this class, customize an Object
3. In order to facilitate the access of other programs to the custom object, you can provide some external access methods
These three parts are embodied in code:
1. Privatize the constructor
2. Create an object of this class in a class
3. Provides a way to get to the object
Packagecom.dreamly.day02;/** * @authordreamly **/ Public classSingledemo {/*** Principle: To define a single case, it is recommended to use the A hungry man-type, lazy-type in concurrency prone to the instantiation of confusion, only locking and multi-threaded double judgment to solve the problem, compared to the A Hungry man type, the code is longer than the number of judgments and time-consuming effort **/ Public Static voidMain (string[] args) {single S1=single.getinstance (); Single S2=single.getinstance (); System.out.println (S1==S2); }}/** This is the first initialization object * called: a hungry Man * A single class entered memory, the object is already created/* Class single{Private () {} private static a s=new s Ingle (); public static single getinstance () {return s; }}*//** The object is initialized when the method is called, and also called the object's lazy load * known as: Slacker * Single class into memory, object does not exist, only object is established when the GetInstance method is called*/classsingle{Private StaticSingle s=NULL; PrivateSingle () {}; Public StaticSingle getinstance () {if(s==NULL) { synchronized(Single.class) { if(s==NULL) {s=NewSingle (); } } } returns; }}
---restore content ends---
Java Learning Single-instance mode (a hungry man and lazy)