Depth exploration Java Singleton design pattern mode

Example ensures that only a single mode to create an object having a global access point at a given time instance. This is one of the most commonly used object-oriented programming techniques. Although it is simple, but from the perspective of class design point of view is probably the easiest, but in trying to achieve before they must solve some minor problems. This article is in sharp distinctions finished learning lesson JAVA architecture VIP course - after [framework] source topic of "learning the source code of good design patterns," wrote the study perception. To in-depth exploration of this model by reference Java code examples.

 

Overview

In some cases, the system should allow only a class of objects stored in memory at a given point in time. This means that, when the program to instantiate the object, the program should not be allowed to create other objects of that class. For example, the connection to the database system, only one connection object to manage the database. This ensures that other objects can not initialize unnecessary connections to drop since multiple instantiations of the overall system performance. Connection and observe the performance by creating multiple JDBC, it can easily be tested. Performance will be affected or significantly reduced. Singleton pattern substantially ensure that the system can only create an instance of the class.

 

Singleton

Singleton pattern is instantiated to ensure that a given class and only one standard technique of an object. This is one of twenty four design mode "Gang of Four" discussions. The idea is to solve a single instance of such class is instantiated, the issue of access to the class instantiation process unique instance of the class or control. The key technology to achieve this is by using a private constructor hidden modifiers, and provides a method for application checked and verified to ensure that only create an instance of the class.

It's very simple, but effectively meet demand. In fact, by applying the same principle, we can control the exact number of instances of the class is created, but is not limited to a single instance. However, here we focus only on a single instance.

 

Use singleton

In fact, we just need to find that case an instance of a class in memory. Multiple objects could damage or cause of damage to the performance of applications that are running. In object-oriented programming, running applications typically have many objects in memory, they interact and play a vital role in the implementation process. However, when implementing a thread pool, cache, or dialog box is responsible for the object preferences and registry settings, database connections, logging, acts as a peripheral situation or graphics card device driver objects are all we want. Running a single instance of the object; otherwise, it will create many problems, such as blocked resources, memory overload and many other inconsistent behavior. This is what we need to determine the appropriate class implements the Singleton pattern and place the appropriate design.

 

Example single-mode

This is the fast implementation of the model.

 1 public final class Singleton {
 2    private static final Singleton singleInstance =
 3       new Singleton();
 4    private Singleton(){
 5    }
 6    public static Singleton getInstance(){
 7       return singleInstance;
 8    }
 9 }
10  
11 public class TestSingleton {
12    public static void main(String[] args){
13       Singleton s1;
14       Singleton s2;
15       s1 = Singleton.getInstance();
16       s2 = Singleton.getInstance();
17       if(s1 == s2){
18          System.out.println("References to same
19             Singleton object");
20       }
21    }
22 }

 

Singleton class is declared final, can not create any subclasses. This even multiple instances of the limits, even if the class by subclassing. The constructor is declared as private; As a result, only the Singleton class can use this constructor to create a Singleton object. Static Singleton object reference to call the private constructor, and provides only one instance of the class. Call getInstance ()  when the method, only to receive a copy of the reference object.

Here, we use a simple test by creating a class called TestSingleton of another. Such statements are two reference Singleton object and call getInstance () method. We then compare the two references, to ensure that they actually cited the same runtime instance, instead of two different objects.

Sometimes, we just need to create a realization of the first instance only when a static method is called, not before that. In the previous example, static objects are created; the getInstance () method of action is simply to return a reference. In this case, we want to create an object on the first call, called lazy initialization. In addition, we want to call is thread safe; otherwise, it may cause strange behavior or unstable memory leak, causing the JVM to crash. This is an example of realization of this purpose.

 1 public final class Singleton {
 2    private static volatile Singleton singleInstance =
 3       null;
 4    private Singleton(){
 5    }
 6    public static Singleton getInstance(){
 7       if (singleInstance == null) {
 8          synchronized(Singleton.class) {
 9             if (singleInstance == null) {
10                singleInstance = new Singleton();
11             }
12          }
13       }
14       return singleInstance;
15    }
16 }
17  
18 public class TestSingleton {
19    public static void main(String[] args){
20       Singleton s1;
21       Singleton s2;
22       s1 = Singleton.getInstance();
23       s2 = Singleton.getInstance();
24       if(s1 == s2){
25          System.out.println("References to same
26             Singleton object");
27       }
28    }
29 }

 

Enum may also be used to achieve a single embodiment. In fact, where possible, it is preferably used instead of classes to implement Enum singleton pattern. JVM is created to ensure that only a single example from an Enum instance.

 1 public enum SingletonEnum {
 2    SINGLEINSTANCE;
 3    public void someMethod(){
 4       // ...
 5    }
 6 }
 7  
 8 public class TestSingleton {
 9    public static void main(String[] args){
10       SingletonEnum s1;
11       SingletonEnum s2;
12       s1 = SingletonEnum.SINGLEINSTANCE;
13       s2 = SingletonEnum.SINGLEINSTANCE;
14       if (s1 == s2){
15          System.out.println("References to same
16             Singleton object");
17       }
18    }
19 }

 

in conclusion

As usual, the user discretion is key to good design, because improper use of the Singleton pattern may lead to other problems. If a single embodiment heavyweight and perform complex operations, it is difficult to test. Better is to use the recommended injection frameworks rely on a single object to construct. In the case such as creating dialog in GUI applications with little or concurrent users, the best single example. Singleton, while useful, notorious for causing performance bottlenecks large scalable application.

Thanks for reading! Welcome messages. Would like to explore more in-depth study also welcome private letter to me. Part II continues ~

Guess you like

Origin www.cnblogs.com/youruike-/p/12058312.html