Design pattern Notes--Singleton mode

Source: Internet
Author: User

Singleton mode, also known as single-state mode or single-piece mode.

Definition: Guarantees that a class has only one instance and provides a global access point to access it. The singleton is typically used to represent system components (resources) that are inherently unique.

Purpose: Control a particular class to produce only one object.

A singleton pattern can be divided into stateful and stateless. Stateful singleton objects are generally also mutable singleton objects, where multiple singleton objects can serve as a state warehouse. An object without a state is an immutable singleton object that simply serves as a tool function.

A hungry man: first new out instance, then return.

1  Public classSingleton {2 3     Private StaticSingleton instance =NewSingleton ();4 5     PrivateSingleton () {6 }7 8      Public StaticSingleton getinstance () {9       returninstance; Ten } One  A}

Lazy: A new instance when called. Using synchronized to prevent multi-threaded environments from producing multiple instances, a hungry man does not exist.

 

1  Public classSingleton {2     Private StaticSingleton instance =NULL;3 4     PrivateSingleton () {5     }6     7      Public Static synchronizedSingleton getinstance () {8         if(Instance = =NULL) {9Instance =NewSingleton ();Ten         }   One          A         returninstance; -     }         -}

Both of the above implementations have lost polymorphism and are not allowed to be inherited.

The way with the registry

Implementation with Registry (HASHMAP):

1 ImportJava.util.HashMap;2 3  Public classSingleton4 {5     Private StaticHashMap Sinregistry =NewHashMap ();6 7     StaticSingleton () {}8 9      Public StaticSingleton getinstance (String name) {Ten         if(Name = =NULL) { OneName = "Singleton"; A         } -  -         if(Sinregistry.get (name) = =NULL) { the             Try { - sinregistry.put (name, Class.forName (name). newinstance ()); -}Catch(Exception e) { - e.printstacktrace (); +             } -         } +  A         return( Singleton) (Sinregistry.get (name)); at     } -      -      Public voidTest () { -System.out.println ("getclasssucess!"); -     }       - } in  -  Public classSingletonChild1extendsSingleton to { +      PublicSingletonChild1 () {} -  the      Public  StaticSingletonChild1 getinstance () { *         return(SingletonChild1) Singleton.getinstance ("SingletonChild1"); $     }Panax Notoginseng  -      Public voidTest () { theSystem.out.prinln ("getclasssuccess111!"); +     } A}

Pitfalls of Singleton mode in Java:

1. Multiple virtual machines, or distributed systems, can create an instance object under each virtual machine when the system singleton is copied to run under multiple virtual machines. Therefore, you should avoid using the simple interest mode when using distributed systems.

2. Multiple ClassLoader, when there are multiple classloader, because different ClassLoader use different namespace to distinguish the same class, therefore, the Singleton class will produce multiple singleton objects in the multi-loader environment.

3. Wrong synchronization, when using lazy mode to understand the synchronization, otherwise it will cause a deadlock error or can not get a singleton effect. The problem does not exist in the A Hungry man mode.

4. Subclass destroys Object control

5. Serialization. A serialized object creates a new object each time the serialization is returned, not just a reference to the original object. To prevent this, in addition to adding implements Serializable to your life, you can also add readresolve methods to a single case.

Always singleton: public static final Singleton INSTANCE = new Singleton ();

Design pattern Notes--Singleton mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.