A single example model for Java design pattern exploration

Source: Internet
Author: User

Singleton mode is a common design pattern in the development of projects in peacetime, the use is more common, the information on the Internet is a catch a lot, small Alan also come to join in the fun, for the future to enrich the content of the design pattern related to do a simple opening.

A singleton pattern is a pattern of creating objects that produces a specific instance object of the class, a little bit different than a normal object creation, except that it ensures that a class in a project only produces a specific object instance. Instead of a second object instance, the third object instance is not present. All use of this object instance is actually the same object, this is the so-called singleton mode, for beginners may be unfamiliar, for the old drivers it is one of the most simple design patterns.

What are the benefits of using singleton mode in Java?

① for frequently used and frequently used objects, it is possible to omit the time it takes to create an object, that is, the need for a new object without an object, for those heavyweight objects, or one less to one, with the old object is better, reduce overhead;

② the number of times the object is created, the frequency of system memory usage decreases, which reduces the pressure on the GC and shortens the time spent by the GC;

When you encounter a class that requires only one instance of an object during the development of a ③ project, it is no doubt that you choose this pattern.

Implementation of the Singleton 1:

Here is a singleton implementation, the implementation is so easy, the code is as follows:

1 /**2 * Single case mode3  * @authorAlanlee4  *5  */6  Public classSingleton7 {8     9     //a hungry man modeTen     Private StaticSingleton instance =NewSingleton (); One      A     PrivateSingleton () -     { -System.out.println ("Singleton is create"); the     } -      -      Public StaticSingleton getinstance () -     { +         returninstance; -     } +      A}

There are a few things you need to pay special attention to when creating singleton objects in this way.

1th: We want to make sure that no one in our project accidentally creates an extra object instance, we need to set the singleton constructor to private. So that other developers can not casually create the object instance of this class, so as to avoid the object instances of the class is wrong to create;

2nd: the instance object must be private and static. If it is not private, then the security of the instance cannot be guaranteed. Inadvertently may be other developers to a singleton.instance=xxx, the object has been changed, if =null, imagine, in the use of this object instance of the use, greet you will be empty object exception of the bosom. Second, because the factory method getinstance () is static, the variables returned in the method are also static.

Discussion: How does each implementation approach perform in a high-concurrency environment, and what are some of the shortcomings of each approach?

The implementation of this singleton mode performance is very good, because the factory method getinstance () Simply return the instance object instance, and there is no lock operation, so in parallel programs, there will be a good performance drop.

However, this approach is a bit inadequate, that is, when the instance object instance is created is not controlled, the basic good know that the static member will be created at the time of the first initialization of the class, this time is not necessarily the factory method getinstance () The first time to be called.

Suppose your singleton pattern is like this, the code is as follows:

1 /**2 * Singleton mode: The first initialization problem of an instance object3  * 4  * @authorAlanlee5  *6  */7  Public classSingleton28 {9      Public Static intSTATUS = 1;Ten  One     Private StaticSingleton2 instance =NewSingleton2 (); A  -     PrivateSingleton2 () -     { theSystem.out.println ("Singleton2 is create"); -     } -  -      Public StaticSingleton2 getinstance () +     { -         returninstance; +     } A  at}

Note that this singleton also contains another static member status. At this point, referencing this status anywhere will cause the instance object instance to be created (any reference to the Singleton2 method or field will cause the class to initialize and create the instance instance, but the class is initialized only once, So instance instances are always created only once).

For example: System.out.println (Singleton.status);

The above println will print out:

As you can see, new Singleton2 () is called even if we do not require the creation of instance singleton objects.

If you don't care about this small deficiency, the implementation of this singleton pattern is a good choice. It is easy to implement, the code is easy to read and the performance is superior.

Implementation of the Singleton 2:

If you want to control instance's creation time accurately, then you need to use the following approach, a policy that supports lazy loading, which only creates objects when instance is used for the first time. The code is as follows:

1 /**2 * Lazy mode with singleton mode3  * 4  * @authorAlanlee5  *6  */7  Public classLazysingleton8 {9     Private StaticLazysingleton instance =NULL;Ten  One     PrivateLazysingleton () A     { -System.out.println ("Lazysingleton is create"); -     } the  -      Public Static synchronizedLazysingleton getinstance () -     { -         if(Instance = =NULL) +         { -Instance =NewLazysingleton (); +         } A         returninstance; at     } -}

Initially we did not need to instantiate the instance object instance, only the factory method GetInstance () was first called to create the Singleton object. However, in a high concurrency environment, in order to prevent objects from being created, we have to use synchronized to synchronize the methods. The benefit of this implementation is that it takes advantage of lazy loading to create objects only when they are really needed. But the disadvantage is also obvious, the concurrent environment lock, in the lock competition when the performance will have a certain impact.

In addition, there is a method called double-check mode that can be used to create a singleton. This is a very ugly and complex method, even in the lower version of the JDK is not guaranteed correctness. It is not recommended, nor is it necessary to spend too much time on this method.

Implementation of the Singleton 3:

In the above example of the implementation of the single mode, can be said to be different, then the third way is the combination of the advantages of a two-way approach, the code is as follows:

1 /**2 * Impeccable single case mode3  * 4  * @authorAlanlee5  *6  */7  Public classStaticsingleton8 {9     Ten     PrivateStaticsingleton () One     { ASystem.out.println ("Staticsingleton is create"); -     } -  the     Private Static classSingletonholder -     { -         Private StaticStaticsingleton instance =NewStaticsingleton (); -     } +  -      Public StaticStaticsingleton getinstance () +     { A         returnsingletonholder.instance; at     } -      -}

The code above implements a singleton pattern and has the advantages of the first two methods. First, the Factory method getinstance () does not use a synchronous lock, which improves performance in high-concurrency environments. Second, an instance of Staticsingleton is created only if the factory method getinstance () is called for the first time. This approach cleverly uses the initialization of the inner classes and classes. The inner class Singletonholder is declared private, which makes it impossible for us to access and initialize it externally. We can only initialize the Singletonholder class within the factory method getinstance () and create a singleton object with the class initialization mechanism of the virtual machine.

Concluding remarks: Chongrubujing, leisure to see before the court flowers and fall, or not inadvertently, diffuse with the outer cloud cirrus ... Little Alan likes to read technical books, but also a martial arts fantasy fiction lover! I hope that the road on it can be like the hero of the novel, even though the difficulties, but also can be the success of the path, as to sit around the beautiful woman, little Alan can not think Ah, or there is a deep love their woman enough.

Cute bo master: Alanlee

Blog Address: Http://www.cnblogs.com/AlanLee

This article is from the blog garden, welcome everyone to join the blog park.

A single example model for Java design pattern exploration

Related Article

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.