Why use singleton design mode?
Suppose a tool class (tools) with an array of operations is designed, there is a hammer method (Hammer), and if you do not use the singleton design pattern, each time you want to invoke the Hammer method, you need a new tools class.
1 classtools{2 //Hammer3 Public voidHammer () {4SYSTEM.OUT.PRINTLN ("Use the Hammer");5 }6 }7 8 Public classToolsdemo {9 Public Static voidMain (string[] args) {Ten //need to use a hammer One NewTools (). Hammer (); A //need to use a hammer - NewTools (). Hammer (); - //need to use a hammer the NewTools (). Hammer (); - } -}
Run results
Using a hammer with a hammer use a hammer
This is a waste of memory resources, like a class of people eat walnuts need to hit with a hammer, there is no need for each student to buy a hammer, just buy a hammer, who want to eat walnuts who go with a hammer, greatly saving the cost.
So it leads to the singleton single-case design mode, only need to generate in memory once, later want to use just call this memory, there is no need to re-in the heap every time new tools class
1 classtools{2 //(1): You must first create a static object in this class3 Private StaticTools instance =NewTools ();4 //(2): privatization of its own constructor to prevent the outside world from creating new objects through the constructor5 PrivateTools () {}6 //(3): Additional exposure to a public static method used to obtain its own object7 Public StaticTools getinstance () {8 returninstance;9 }Ten One //Hammer A Public voidHammer () { -SYSTEM.OUT.PRINTLN ("Use the Hammer"); - } the } - - Public classToolsdemo { - Public Static voidMain (string[] args) { + //need to use a hammer - tools.getinstance (). Hammer (); + //need to use a hammer A tools.getinstance (). Hammer (); at //need to use a hammer - tools.getinstance (). Hammer (); - } -}
Run results
Using a hammer with a hammer use a hammer
Java Learning Note (24): Single case design mode singleton