Singleton design Pattern: guarantees that a class has only one instance and provides a global access point to access it
1. Privatization of construction methods
2. Declaring an object of this class
3. Provide an external static method to obtain an object instance
Two ways of realization: A hungry man type and lazy type
under what circumstances should it be used? when there is no attribute in a class (the state of the object), the class is used very frequently as a tool class;
benefit: Save memory (because objects are constantly being created consumes memory)
1 Public classPractice14 {2 3 Public Static voidMain (string[] args) {4 //TODO auto-generated Method Stub5Single s=single.getinstance ();6 S.method ();7 } 8 }9 //a hungry man typeTen classsingle{ One Private StaticSingle single=NewSingle (); A PrivateSingle () {//construction method Privatization, in order to prevent the instantiation of objects outside of this class - - } the Public StaticSingle getinstance () { - returnSingle ; - } - Public voidmethod () { +System.out.println ("Method"); - } + } A //Lazy Type at classsingle2{ - Private StaticSingle2 single=NULL; - PrivateSingle2 () {//Structuring Method Privatization - - } - Public StaticSingle2 getinstance () { in if(single==NULL){ -single=NewSingle2 (); to } + returnSingle ; - } the Public voidmethod () { *System.out.println ("Method"); $ }Panax Notoginseng}
Java Object-oriented _ single case design pattern