One, Singleton mode: A commonly used software design mode. The singleton mode ensures that the class with the pattern can have only one instance of the class that is used in the system. That is, a class has only one instance of an object
Second, application: thread pool, cache, log Object, dialog box, printer, video card driver object is often designed as a singleton
Three, the characteristics of single-case mode:
1, the Singleton class can have only one instance.
2, the Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.
Iv. creation of the simple interest model
Public classSINGLETN {PrivateString name; PrivateString ID; //Create a unique instance Private StaticSingletn SINGLETN =NewSingletn (); //providing examples to outsiders Public Staticsingletn getinstant () {returnSingletn; } //Constructor Privatization PrivateSingletn () {} Public voidsetName (String name) { This. Name =name; } Public voidsetId (String id) { This. ID =ID; } PublicString GetName () {returnname; } PublicString getId () {returnID; }}a hungry man single-case mode
Public classSINGLETN {PrivateString name; PrivateString ID; //Create a unique instance Private StaticSINGLETN Singletn; //providing examples to outsiders Public Staticsingletn getinstant () {if(Singletn = =NULL){//double check synchronized(SINGLETN.class){//Thread -safety issues, locking for thread synchronization when multi-threadingsingletn=NewSingletn (); } } returnSingletn; } //Constructor Privatization PrivateSingletn () {} Public voidsetName (String name) { This. Name =name; } Public voidsetId (String id) { This. ID =ID; } PublicString GetName () {returnname; } PublicString getId () {returnID; }}Lazy Single-case mode
A hungry man and lazy-type difference:
1. A hungry man is the static initialization method, which is the object that the class is loaded on, so the system resources should be used in advance.
2. Lazy type similar to lazy loading, in use when the instantiation, multi-threaded thread security issues, need double check
It is recommended to use a hungry man style.
java-Single-Case mode