Design Patterns: Singleton

Singleton

Singleton (Singleton Pattern) is one of the easiest in Java design patterns. This type of design pattern belongs create schema, which provides the best way to create objects.

This model involves a single class that is responsible for creating your own objects, while ensuring that only a single object is created. This class provides the only way to access the object can directly access, no instance of the object class.
note:

  1. Only one singleton class instance.

  2. Singleton class must create their own unique instance.

  3. Singleton class must provide this example to all other objects.

Introduction

Intent: to ensure that only one instance of a class, and provide a global access point to access it.

Mainly to solve: a global classes used to create and destroy frequently.

How to solve: to determine whether the system already has this single case, if it returns, if not then created.

The key code: the constructor is private.

Application examples: such as Hibernate's SessionFactory, he acts as a proxy data storage source, and is responsible for creating Session objects. SessionFactory not lightweight, under normal circumstances, a project usually requires only a SessionFactory enough, then it will use the Singleton pattern

Be used: 1, requires the production of a unique serial number. 2, WEB counters, do not always have time to refresh, single cases of congenital cached in the database Riga. 3, an object needs to create excessive consumption of resources, such as I / O connections to the database and so on.

Several implementations of singleton pattern

1, hungry Chinese type (static constants)

Code examples:

public class SingletonDemo1 {

    private final static SingletonDemo1 instance = new SingletonDemo1();

    private SingletonDemo1(){}

    public static SingletonDemo1 getInstance(){
        return instance;
    }
}

Are Lazy Initialization : No

Are multi-thread safe : Yes

Realize the difficulty : Easy

Description: This method commonly used, but prone garbage objects.
Advantages: not locked, the efficiency will improve.
Disadvantages: initialized when the class is loaded, wasting memory.
It is based on classloder mechanism avoids the synchronization problem multithreading, however, instance to instance of the class is loaded at the time, although there are causes class loading are many, most of them in singleton mode are calling getInstance method, but it can not be determined there are other ways (or other static methods) leads the class loader, which apparently did not reach instance initialization lazy loading effect.

2, starving formula (static code block)

Code examples:

public class SingletonDemo {

    private final static SingletonDemo instance;

    private SingletonDemo(){}

    static{
        instance = new SingletonDemo();
    }

    public static SingletonDemo getInstance(){
        return instance;
    }
}

The first analysis of the same

3, lazy man's (thread safe)

public class SingletonDemo {

    private static SingletonDemo instance;

    private SingletonDemo(){

    }

    public static SingletonDemo getInstance(){

        if(instance == null){
            instance = new SingletonDemo();
        }
        return instance;
    }

}

Are Lazy Initialization: Yes

Are multi-thread safe: No

Achieve Difficulty: Easy

Description: This is the most basic way of implementation which achieved the biggest problem is not support multi-threading. Because there is no lock synchronized, so strictly speaking it is not a singleton.
Obviously this way lazy loading, does not require thread-safe, can not work in multi-threaded properly.

4, lazy formula (synchronization method)

public class SingletonDemo4 {

    private static SingletonDemo4 instance;

    private SingletonDemo4(){

    }

    public static synchronized SingletonDemo4 getInstance(){

        if(instance == null){
            instance = new SingletonDemo4();
        }
        return instance;
    }

}

Are Lazy Initialization: Yes

Are multi-thread safe: Yes

Achieve Difficulty: Easy

Description: in this way have a good lazy loading, can work well in multi-thread, however, is very low efficiency, 99% of cases does not require synchronization.
Pros: The first call was initialized, to avoid wasting memory.
Cons: Must be locked synchronized to ensure a single case, but the lock will affect the efficiency.
Performance getInstance () the application is not critical (which use less frequently).

5, lazy formula (sync block)

public class SingletonDemo5 {

    private static SingletonDemo5 instance;

    private SingletonDemo5(){

    }

    public static  SingletonDemo5 getInstance(){

        if(instance == null){
            synchronized(SingletonDemo5.class){
                instance = new SingletonDemo5();
            }
        }
        return instance;
    }

}

6, the subject double lock / lock double check (the DCL, i.e., double-checked locking)

public class SingletonDemo6 {

    private static SingletonDemo6 instance;

    private SingletonDemo6(){

    }

    public static SingletonDemo6 getInstance(){

        if(instance == null){
            synchronized(SingletonDemo6.class){
                if(instance == null){
                    instance = new SingletonDemo6();
                }
            }
        }
        return instance;
    }

}

Are Lazy Initialization: Yes

Are multi-thread safe: Yes

Realize the difficulty: more complex

Description: This dual mode locking mechanism, and in safe multithreading can maintain high performance.
Performance getInstance () is critical to the application.

7, register-based / static inner classes

public class SingletonDemo7 {

    private SingletonDemo7(){

    }
    private static class SingletonInstance {
        private static final SingletonDemo7 INSTANCE = new SingletonDemo7();
    }

    public static synchronized SingletonDemo7 getInstance(){
        return SingletonInstance.INSTANCE;
    }

}

Are Lazy Initialization: Yes

Are multi-thread safe: Yes

Realize the difficulty: General

Description: This method can achieve the same effect double check the lock mode, but the implementation is simpler. Initialization of the static field using a delay, this mode should be used instead of double lock detection mode. This embodiment applies only to the static field, the double lock detection mode can be used when a delay required to initialize instance fields.
In this way the same advantage classloder mechanism to ensure that only one thread at initialization instance, it is now the third ways are different: The first three ways as long as the Singleton class is loaded, the instance is instantiated (not reached lazy loading effect), but this approach is being loaded Singleton class, instance may not be initialized. Because SingletonInstance class is not actively used, only displayed when invoking getInstance method appears SingletonInstance loading classes to instantiate instance. Imagine, if you instantiate instance is resource-consuming, so want it to delay loading, on the other hand, do not want to load when the class is instantiated Singleton, Singleton class because they can not ensure that the initiative may also be used in other places in order to be loaded, this time to instantiate instance clearly inappropriate. This time, in this way compared to the first three kinds of ways it is very reasonable.

8, enumerate

public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() { 
	
	}  
}

Are Lazy Initialization: No

Are multi-thread safe: Yes

Achieve Difficulty: Easy

Description: This implementation has not been widely adopted, but this is the best way to achieve single-mode embodiment. It is more compact, automatic support serialization mechanism to prevent multiple instances of the absolute.
This approach is advocated Effective Java author Josh Bloch way, it can not only avoid multi-thread synchronization problems, but also automatically supports serialization mechanism to prevent deserialization re-create a new object, absolutely prevent multiple instantiation. However, only joined the enum properties after JDK1.5, write in this way can not help but feel strange, in practice, rarely used.
Not by reflection attack to call the private constructor.

Published 40 original articles · won praise 9 · views 20000 +

Guess you like

Origin blog.csdn.net/aawmx123/article/details/101169794