Even those of you who don’t understand design patterns have probably heard of singleton patterns and used them in your projects. But how many people really understand and are familiar with the singleton pattern? Let’s take a look at one of the simplest design patterns, the singleton

Why singleton pattern?

Baby, you are the only one for me. It is not easy to go back when both worlds have changed shape. . Cough cough ~ first sing this bar, into the topic. Every time I mention singleton, I hum wang Lee-hom’s the Only. Why is that? What appeals to me about this song? It’s the word “only,” which is a very dirty word.

In Stalin’s Soviet Union, the personality cult reached considerable proportions. But why does it lead to a cult of personality? It is very simple, “There is only one Stalin, there is only one leader”! Two or more leaders were not allowed, and Stalin was needed to call the shots on matters of state affairs, diplomacy and so on.

define

Ensure that there is only one instance of a class and that the entire system can access that instance.

The characteristics of

  1. A singleton class guarantees only one instance
  2. A singleton class must create its own unique instance
  3. The singleton class provides that unique instance to the system

The definition of a singleton is that simple, don’t you understand? In plain English, only one object can be new in this class, and no second object can be new, which is what the system accesses. What way is there to ensure that there is only one leader, Stalin? Two more common ways: hungry and lazy

Second, the actual combat

UML diagrams

One tip is that UML diagrams make it easier for you to understand the core of a design pattern in depth when studying it. Moreover, UML diagrams are an essential skill to be a project manager.

Singleton UML diagram. PNG

In the code

How do I ensure that a system produces only one instance? The constructor must be decorated with private and instantiated inside the constructor.

Two common approaches to the singleton pattern were mentioned earlier: hungrier and slacker. Here’s how hungry you really are — and how lazy you really are!

1. Hungry

First, take a look at the Hunchman singleton pattern.

Hangry singleton code is as follows:

public class EagerSingleton {

    private static EagerSingleton singleton = new EagerSingleton();

    private EagerSingleton() {
    } 

    public static EagerSingleton getSingleton() {
        returnsingleton; }}Copy the code

Note that you must use a static method to get the instance, otherwise you can’t get a unique instance from that method outside the class.

Hungry, as the name implies, can’t wait to instantiate when it’s needed externally, so creating an object instance while loading a class is a good example of self-reliance

The main problem with hanchian singletons is that since classes are already loaded at initialization, they must consume memory.

2. Slacker style

The lazy singleton code looks like this:

public class LazySingleton {

    private static LazySingleton singleton = null;

    private LazySingleton() {
    }

    public static synchronized LazySingleton getSingleton() {
        if (instance == null) {
            singleton = new LazySingleton();
        }
        returnsingleton; }}Copy the code

Synchronized is used for synchronization to ensure thread-safety

The definition of “lazy” is also easy to understand, because lazy creates object instances only when they are needed, and does not instantiate classes until then.

The main problem with lazy singletons: Because its implementation is thread-safe, it slows down access to the instance and requires judgment every time.

At this point, since there are problems with both singletons, is there a way to keep performance low and thread-safe? Many of the existing sources on the web mention double-checked locking, which I thought was cumbersome when I first saw it, as well as its implementation. Volatile is not recommended because it affects performance, so I won’t cover it here. Of course, the choice of which way is based on the actual situation of the individual project to choose.

Before you go, the next step is a more perfect way to implement singleton pattern enumeration singleton

3. Enumerate singletons

As usual, the code first:

public enum Singleton {

    singleton;

    public void singletonFunc() {// What the singleton needs to do}}Copy the code

Isn’t that easy? And because of the automatic serialization mechanism, the thread is absolutely safe. Three words: simple, efficient and secure

Third, summary

Well, that concludes the first installment of the design Patterns series. If you think you need improvement or support from the author, please leave a comment below. The first mode is easy for everyone to understand, but the next is the big one. The next design pattern is factory method pattern.

Design pattern making Java source code download: https://github.com/jetLee92/DesignPattern

The development of AndroidJet