java's singleton pattern (big talk design pattern)

I remember that I was asked about this pattern when I went to the interview. I had not seen the design pattern at that time, and I knew nothing about the design pattern, but I can be sure that I used the single pattern. At that time, the answer was very awkward.

From then on, I began to learn design patterns. What we're talking about today is the singleton pattern. There are many times when we want a class to be instantiated only once. For example, the Method we often use is the most typical singleton pattern. Of course, there are also singleton patterns in many frameworks.

First look at the class diagram:

Dahua design pattern class diagram

The single case model can be divided into lazy type and hungry type. First look at the writer's demo.

/**
 * Hungry Han style
 */
public class SingleDemo {

    private static SingleDemo singleDemo = new SingleDemo();

    private SingleDemo() {

    }

    public static SingleDemo getInstance() {
        return singleDemo;
    }
}
/**
 * Slovenly
 */
public class SingleDemo2 {

    private static SingleDemo2 singleDemo2 = null;

    private SingleDemo2() {

    }

    public static SingleDemo2 getInstance() {
        if (null == singleDemo2) {
            synchronized (SingleDemo2.class) {
                if (null == singleDemo2) {
                    return singleDemo2 = new SingleDemo2();
                }
            }
        }
        return singleDemo2;
    }
}
/**
 * Internal lazy
 */
public class SingleDemo3 {

    private SingleDemo3() {

    }

    private static class SingleHold {
        private static SingleDemo3 singleDemo3 = new SingleDemo3();
    }

    public static SingleDemo3 getInstance() {
        return SingleHold.singleDemo3;
    }
}
/**
 * client
 */
public class Test {

    public static void main(String[] args) {

        SingleDemo singleDemo = SingleDemo.getInstance();
        SingleDemo singleDemo1 = SingleDemo.getInstance();
        System.out.println(singleDemo == singleDemo1);

        SingleDemo2 singleDemo2 = SingleDemo2.getInstance();
        SingleDemo2 singleDemo21 = SingleDemo2.getInstance();
        System.out.println(singleDemo2 == singleDemo21);

        SingleDemo3 singleDemo3 = SingleDemo3.getInstance();
        SingleDemo3 singleDemo31 = SingleDemo3.getInstance();
        System.out.println(singleDemo3 == singleDemo31);
    }
}

 

Operation result:

true
true
true

 

The author recommends you to use the internal form. There are many differences among them. I am lazy to give you an address http://www.cnblogs.com/coffee/archive/2011/12/05/inside-java-singleton.html

Above, I hope to help you learn the single example mode.

Keywords: Java

Added by skope on Thu, 21 May 2020 18:26:36 +0300