Singleton appreciated / use

Rookie Tutorial | 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.

One, three private a public:

①, private static property, again the only store objects generated

②, private constructor

③, clone private function, preventing clone --clone

④, public static method used to access objects stored in static properties, if no object, this embodiment generates single

Second, keyword instanceof

Check this variable is an object that implements the interface class, subclass, or.

1, of a private __construct is necessary, singleton class can not be instantiated in other classes, can be instantiated itself;
2, has saved instance of a static member variable of the class;
3, a public static method examples in this class, and access instances of this class;

 

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.

When to use: when you want to control the number of instances, to save system resources.

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.

Applications:

  • 1, a class only a teacher.
  • 2, Windows is a multi-process multi-threaded, when a file operation, it inevitably multiple processes or threads simultaneously operating a file of the phenomenon, the processing of all files must be done by a unique instance.
  • 3, some devices are often designed as a single Manager embodiment mode, such as a computer printer has two, when both the output will not process the same document printer.

advantage:

  • 1, only one instance in memory, reducing memory overhead, especially frequent create and destroy instances (such as School of Management Home page cache).
  • 2. Avoid multiple assignment of resources (such as file write operations).

Cons: no interface, not inherited, and the conflict single responsibility principle, a class should only be concerned about the internal logic, not on the outside how to be instantiated.

scenes to 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.

Note: getInstance () method requires the use of synchronization lock synchronized (Singleton.class) to prevent multiple threads into the cause instance is instantiated multiple times.

achieve

We will create a  SingleObject  class. SingleObject  class has its own private constructor and a static instance.

SingleObject  class provides a static method, for the outside world to get its static instance. SingletonPatternDemo , our demo class uses  SingleObject  class to get  SingleObject object.

UML diagram singleton

step 1

Creating a Singleton class.

SingleObject.java

 

public class SingleObject {
 
   //创建 SingleObject 的一个对象
   private static SingleObject instance = new SingleObject();
 
   //让构造函数为 private,这样该类就不会被实例化
   private SingleObject(){}
 
   //获取唯一可用的对象
   public static SingleObject getInstance(){
      return instance;
   }
 
   public void showMessage(){
      System.out.println("Hello World!");
   }
}

Step 2

Get a unique object from singleton class.

SingletonPatternDemo.java

public class SingletonPatternDemo {
   public static void main(String[] args) {
 
      //不合法的构造函数
      //编译时错误:构造函数 SingleObject() 是不可见的
      //SingleObject object = new SingleObject();
 
      //获取唯一可用的对象
      SingleObject object = SingleObject.getInstance();
 
      //显示消息
      object.showMessage();
   }
}

Step 3

The implementation of the program, output:

Hello World!

Several implementations of singleton pattern

Single-mode embodiment of a variety of ways, as follows:

1, lazy style, thread safe

Are Lazy Initialization: is

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 manner lazy loading, does not require a security thread, multi-thread work can not be normal.

Examples

 

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
  
    public static Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

The next several implementations described support multithreading, but differ in performance.

2, lazy style, thread-safe

Are Lazy Initialization: is

It is multi-thread safe: is

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).

Examples

 

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

3, hungry Chinese style

Are Lazy Initialization: No

It is multi-thread safe: is

Achieve Difficulty: Easy

Description: In this manner 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 classloader 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.

Examples

 

public class Singleton {  
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
    return instance;  
    }  
}

4, double lock detection / double checking lock (the DCL, i.e., double-checked locking)

JDK version: JDK1.5 from

Are Lazy Initialization: is

It is multi-thread safe: is

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.

Examples

 

public class Singleton {  
    private volatile static Singleton singleton;  
    private Singleton (){}  
    public static Singleton getSingleton() {  
    if (singleton == null) {  
        synchronized (Singleton.class) {  
        if (singleton == null) {  
            singleton = new Singleton();  
        }  
        }  
    }  
    return singleton;  
    }  
}

5, register-based / static inner classes

Are Lazy Initialization: is

It is multi-thread safe: is

Realize the difficulty: General

Description: in this way 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 use of the same classloader mechanisms 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 SingletonHolder class is not actively used, only through explicit call getInstance method will explicitly load SingletonHolder class to instantiate instance. Imagine, if you instantiate instance is resource-consuming, so let it delay to load, on the other hand, do not want to load when you instantiate the class 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.

Examples

 

public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
}

6, enumerate

JDK version: JDK1.5 from

Are Lazy Initialization: No

It is multi-thread safe: is

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.

Examples

 

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

Rule of thumb: Under normal circumstances, is not recommended to use the first type and second type lazy, it is recommended to use three kinds of ways hungry man. To achieve clear only when lazy loading effect, will use the first five kinds of ways to register. If it comes to deserialize create an object, you can try sixth enumeration method. If you have other special needs, you can consider using a fourth double check the lock mode.

Guess you like

Origin blog.csdn.net/LQZ8888/article/details/90404036