[] Singleton Design Pattern

Foreword

Singleton design pattern, to ensure that there is only a global instance of the class. The constructor is declared as private, to prevent the call (although you can still use reflection to call). Declare a static instance of a class in the class, declare a public method to get the instance. This blog gives a simple implementation, thread-safe analysis of how to do, organize the disadvantages of using a Singleton.

Thread Safety

One thread-safe method, when the class is loaded, initializes this member, Java Runtime library is to use this method.
Method two is not thread safe. If multiple threads into the function (critical section), it will return a number of different instances.

Code verification

The following code is verified thread-safe, that is the case of multi-threading method of the second can not guarantee true "singleton." HashCode displayed by printing each class, class instances are not unique.

class Singleton {
    private static Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            try {
                Thread.sleep(233);
                singleton = new Singleton();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        return singleton;
    }
}

public class Main {
    public static void main(String args[]) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    Singleton singleton = Singleton.getInstance();
                    System.out.println(singleton.hashCode());
                }
            }).start();
        }
    }
}

solution

A simple approach is to getInstance declared as synchronized low efficiency, because each thread waiting to enter the critical section.

Another method is called Double Checked Locking (DCL), the common variables declared volatile (every time you want to use this variable, taken from memory out to ensure that each thread can see the changes this variable).

class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            try {
                Thread.sleep(233);
                synchronized (Singleton.class) {
                    if (singleton == null) {
                        singleton = new Singleton();
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        return singleton;
    }
}

harm

So what's bad, do not blame this design patterns, global variables are wrong.

1, global variables

Singleton management of public resources, anywhere in the code, just call the method to get the Singleton instance, you can get to the Singleton instance, can read and write to these public resources. This makes Singleton became a global variable.

Harm global variables, Singleton also disadvantages. The use of scenarios and advantages of the global variables of its own global variables, to separate the two sides look at, where they talk about the downside of global variables not want to say nothing.

Before analyzing the disadvantages of global variables, in [2] below we saw a very interesting analogy:

Using global state with your fellow programmers is like using the same toothbrush with your friends - you can but you never know when someone will decide to shove it up his bum.

I want the man to say this point of view, probably the smell of toothbrush used it. Why not regulate people together to restrain the use of global variables in it?

The man points to the nature of global variables, anyone can use it to do anything, the whole program has brought great uncertainty. Online discussion about the harm many global variables, the following compiled some, though not very bad:

  1. Codes higher degree of coupling. Suppose some functions are dependent on global state variables, these functions are linked together by a global variable. A presence modification function effects on reading another function, these functions are virtually linked to together.
  2. To the test difficult. Global variables stored some states, you need to arrange the order of the module can run the correct test. However, the test unit should be independent of each other, rather than sequential.
  3. Multi-threaded write, when to mutually exclusive.
  4. It destroys the function input and output functions. Take global variables to read input, write output.
  5. Naming conflicts.
  6. Reduce readability. To understand a function, also you need to use to track the ins and outs of global variables.

2, undermine the single responsibility principle

Definition: On a category, it should only be one causes of change

When a class uses Singleton time, it is not only responsible for this class need to complete the task, is also responsible for the creation and management of a single object resources. Functions of this class do two tasks, the correlation is low.

This is not really too bad. After all, the design principles do not always need to follow.

use correctly

Mentioned above disadvantages, the core essence is to avoid Singleton used as a global variable. What Singleton usage scenario is it?

Singleton back up the nature of the role, only one instance of this class. Speaking in front of this design pattern undermines the principle of single responsibility, because of the need to manage this instance.

It boils down to the use of this design pattern for two reasons:

(1) a single instance

Management (2) of Example

He told a specific example of using a Singleton in [1]. That is the log (log). Because the essence of the function log and does not generate code coupling, so whether to open the log is not much impact on the functionality of the system.

Reference links

  1. https://stackoverflow.com/questions/228164/on-design-patterns-when-should-i-use-the-singleton
  2. https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
  3. https://stackoverflow.com/questions/26285520/implementing-singleton-with-an-enum-in-java
  4. https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons?page=1&tab=votes#tab-top

Guess you like

Origin www.cnblogs.com/zhouzekai/p/11233617.html