Turn
Single-Instance concept:
In Java, the singleton pattern is a common design pattern, and the singleton pattern is divided into three kinds: lazy type single case, a hungry man type single case, registration type single case three kinds.
There are a few features of the Singleton model:
1, the Singleton class can have only one instance.
2. The Singleton class must create its own unique instance itself.
3. The Singleton class must provide this instance to all other objects.
Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system. In a computer system, the driver objects of the thread pool, cache, log Object, dialog box, printer, and video card are often designed as singleton. These apps have more or less the functionality of the resource manager. Each computer can have several printers, but only one printer Spooler to prevent both print jobs from being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to prevent a communication port from being called simultaneously by two requests. In short, the selection of Singleton mode is to avoid inconsistent state, to avoid long-running political.
Original
When designing a simple banking management system, the number Management machine class (Numbermachine) needs to be designed as a singleton.
The code is as follows:
1 Public classNumbermachine {2 3 //define three member variables i.e., three number Manager common VIP Express4 PrivateNumbermanager commonnummanager=NewNumbermanager ();5 PrivateNumbermanager vipnummanager=NewNumbermanager ();6 PrivateNumbermanager expressnummanager=NewNumbermanager ();7 8 PublicNumbermanager Getcommonnummanager () {9 returnCommonnummanager;Ten } One PublicNumbermanager Getvipnummanager () { A returnVipnummanager; - } - PublicNumbermanager Getexpressnummanager () { the returnExpressnummanager; - } - //This class is made into a single case - //Construction method Privatization so other classes cannot be called only by themselves (by static method calls) + PrivateNumbermachine () {} - //static Statics Method + Private StaticNumbermachine instance=NULL; A Public Staticnumbermachine getinstance () at { - if(instance==NULL){ -Instance=Newnumbermachine (); - } - returninstance; - } in -}
Go to Java class single case