DesignPattern series __10 singleton

Singleton Introduction

Singleton pattern is to ensure that throughout the software decency, the object has only one instance of a class, and the class is typically provide public methods (static methods) a Foreign obtain this instance.
Such as logging, database connection pooling and other objects, and generally requires only one instance of the object, which will use the singleton.

Singleton pattern eight modes

  • Hungry man type (static constants)
  • Starving formula (static code block)
  • Lazy man's (thread safe)
  • Lazy formula (synchronization method)
  • Lazy formula (sync block)
  • Lazy man (double check)
  • Static inner classes
  • enumerate

In order to explain the following:

Hungry man type (static constants)

Typically, the way we create an object that is new, however, when we consider creating only one instance of time, it should be prohibited to be created by new external way. At the same time, inability to use the new, you should consider acquiring a singleton object the way to others.

Thinking

1. The constructor privatization (to prevent external new, but there are limitations on reflection)
internal class to create objects 2.
3. External provide an example of public static method to get

Code is implemented as follows:

public class Singleton1 {
    public static void main(String[] args) {
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();
        HungrySingleton hungrySingleton1 = HungrySingleton.getInstance();
        System.out.println(hungrySingleton == hungrySingleton1);
    }
}

class HungrySingleton {
    //1.私有化构造器
    private HungrySingleton() {
    }

    // 2.类内部创建对象,因为步骤3是static的,
    // 该方法也是static的
    private static HungrySingleton instance = new HungrySingleton();

    //3.对外提供一个获取对象的方法,
    // 因为调用方式的目的就是为了获取对象,
    // 所以该方法应该是static的。
    public static HungrySingleton getInstance() {
        return instance;
    }
}

Run the program shows that we really only creates an object instance.

summary

Advantages: the code is easy to implement, while class loading is complete instantiation, at the same time, the way to avoid thread-safety issues.
Disadvantage: when the class is instantiated loading is completed, the effect did not reach the Lazy Loading. If you have never used this example from start to finish, it will result in a waste of memory.
In this way based on classloder mechanism avoids the synchronization problem multithreading, however, instance to instance of the class is loaded at the time, in most cases a single mode are calling getInstance method, but there are several reasons why the class is loaded, and therefore can not there are other ways to determine (or other static methods) cause the class loader, it will not reach instance initialization lazy loading effect.

Guess you like

Origin www.cnblogs.com/JackHou/p/11316092.html