/*
Design Patterns: The most effective way to solve a class of problems
Design Patterns in Java 23
Singleton design pattern: Resolves a class that only has one object in memory.
Want to guarantee that the object is unique.
1. In order to avoid excessive creation of such objects by other programs. Control Prohibition First
Other programs build objects.
2. In order for other programs to have access to such objects, the
Customize an object in this class.
3. In order to facilitate the access of other programs to custom objects, you can provide external
Some access methods.
How do these three steps show up in code?
1, privatize the constructor. Object creation is not allowed.
2, create an object of this class in the class.
3, provides a method that can be obtained to the object.
*/
Package Jichu51;class person{string name;private person () {};//1. Privatization construction method Static person aperson=new person ();//2. Instantiate this type of object public static person getinstance () {return aperson;}} public class Single {public static void main (string[] args) {//TODO auto-generated method Stubperson a=person.getinstance (); A.name= "Xiao Ming"; Person B=person.getinstance (); System.out.println (B.name);}}
If Sing a = Single.getinstance is called in the main function, how does it change in memory (do that, then execute that, preferably in detail), and if there is a variable Sing b = single.getinstance, why A, b point to the same place, call two times instead of new two times--
For:
Because it is a static variable, the class load is created by the variable s to point to new single (), and the S object is returned when GetInstance is called.
Because the S object belongs to a static member variable, there is a method area instead of the stack. The method area stores only one copy of the item. So even if string b=single.getinstance (). The return is still the only static variable s in the method area. That is, the singleton mode has only one static variable s pointing to the object. No matter how called, there is only one object.
Java Singleton mode