Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Singleton pattern definition and usage scenarios

Definition:

This type of design pattern is the creation pattern, which provides the best way to create objects. This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique objects directly, without instantiating the objects of the class.

How to resolve it: Determine if the system already has this singleton, return it if it does, and create it if it does not.

Usage scenarios

  • 1. Require the production of unique serial numbers.
  • 2. The counters in the WEB are not added to the database every time they are refreshed, but cached with singletons first.
  • 3. Creating an object consumes too many resources, such as I/O connections to the database.

Application examples:

  • There is only one head teacher in a class.
  • 2, Windows is multi-process multi-thread, in the operation of a file, it is inevitable that multiple processes or threads operate a file at the same time, so all file processing must be carried out by a unique instance.
  • 3. Some device managers are often designed in a singleton mode. For example, a computer with two printers has to deal with the fact that two printers cannot print the same file.

Disadvantages: No interface, no inheritance, conflicts with the single responsibility principle, a class should only care about internal logic, not how to instantiate outside.

Several common singleton pattern implementations

Lazy way

  • Ensuring thread safety
  • Prevents instruction reordering
  • Double check optimization
/** * double check slacker mode */
public class SingletonLazy {
    private volatile static SingletonLazy instance;

    private SingletonLazy(a) {}public static SingletonLazy getInstance(a) {
        if (instance == null) {
            synchronized (SingletonLazy.class) {
                if (instance == null) {
                    instance = newSingletonLazy(); }}}returninstance; }}Copy the code

The hungry way

Hungry mode: the instance is initialized at the class loading node

Three stages of class loading (sidebar)

  • Load -> Load the corresponding binary file and create the corresponding data structure in the method area
  • Links -> A. Verify, B. Prepare, C. Parse
  • Initialize -> Assign initial values to static properties

Hungry and Hungry mode example

public class SingletonHungry {
      
   // Static variables are assigned at class load time
    private static SingletonHungry instance = new SingletonHungry();

    private SingletonHungry(a) {}public static SingletonHungry getInstance(a) {
        returninstance; }}Copy the code

Inner class mode

Because a class is only loaded once, you can use this feature to initialize a single real object.

/** * static inner class */
public class SingletonInner {

    static class InnerClass {
        private static SingletonInner instance = new SingletonInner();
    }

    public static SingletonInner getInstance(a) {
        return InnerClass.instance;
    }

    private SingletonInner(a) {
        if(InnerClass.instance ! =null) {
            throw new RuntimeException("Singletons are not allowed to have multiple examples!"); }}}Copy the code

Enumeration methods

Enumeration is a singleton strength

public class SingletonEnum {

    private SingletonEnum(a) {}private enum SingletonInnerEnum {
        INSTANCE;

        private SingletonEnum instance;

        SingletonInnerEnum() {
            this.instance = new SingletonEnum();
        }

        public SingletonEnum getInstance(a) {
            returninstance; }}public static SingletonEnum getInstance(a) {
        returnSingletonInnerEnum.INSTANCE.getInstance(); }}Copy the code

Reference documentation

  • www.runoob.com/design-patt…
  • www.cnblogs.com/binaway/p/8…
  • zhuanlan.zhihu.com/p/33102022