Design mode:
* Design pattern: The most effective way to solve a certain kind of problem;
* Java has 23 design mode
* Singleton design mode: Solve a class in memory only one object exists;
*
* Want to make sure the object is unique
* 1. To avoid excessive creation of such objects by other programs. Control prevents other programs from setting up this type of object first
* 2. In order for other programs to have access to the class object, you have to customize an object in this class
* 3. In order to facilitate the access of other programs to the custom object, you can provide some external access methods
*
* How do these three parts show up in code?
* 1. Privatize a constructor
* 2. To create an object of this class in a class
* 3. Provides a way to get to the object
* How to describe things and how to describe them.
* When you need to guarantee the object of this thing to be unique in memory, add the above 3 parts.
Simple interest design mode: Recommended use of a hungry man type
1. A Hungry man type
1 //initialize the object first, called: a Hungry man type2 //Sinle class creates an object in memory3 4 class Single5 {6 PrivateSingle () {}7 Private StaticSingle S =NewSingle ();8 9 Public StaticSingle getinstance ()Ten { One returns; A } - } - classDanlidemo the { - Public Static voidMain (string[] args) - { -Single SS =single.getinstance (); + } -}
2. Lazy Type
1 //An object is a method that is called when it is initialized, also called an object's lazy loading, known as: Idle-type2 //The Single2 class enters memory, the object does not exist, and the object is created only when getinstance is called. 3 classSingle24 {5 Private StaticSingle2 s =NULL;6 PrivateSingle2 () {}7 Private StaticSingle2 getinstance ()8 {9 if(s = =NULL)Ten { Ones =NewSingle2 (); A returns; - } - } the } - - classDanlidemo - { + Public Static voidMain (string[] args) - { +Single2 SS =single2.getinstance (); A } at}
Java: Single-instance design pattern