No girlfriend come in!! Let's use the singleton mode to write a girlfriend!!

hello, everyone. This is pudding SAMA. The epidemic is over recently. Are you guys going out with your girlfriend?
what?
You don't have friends yet.
Never mind, pudding will teach you to write a girlfriend today.

Start doing things!!

A few days ago, I had a friend who was a single aristocrat. And I've been single for 18 years. One day he came to me and said.

"Pudding, you said that since JAVA can abstract everything into an object, then can you write a girlfriend out?".

"Well!! I think there can be, Sao Nian. Go ahead and be brave enough to create miracles. "


So after ten minutes, my friend came to me with his girlfriend.

"Pudding, pudding, look at this is my girlfriend."

"My girlfriend can go shopping, eat and watch movies with me. Even the later "hey hey"

Pudding: "huh? What is it? I suspect you're playing yellow. "


"What? What is yellow? Hey, hey, hey, it's the two of us telling jokes together in the room. That's why there's a "Hey, hey, hey, hey" voice

oh So it is (strangely only increased).

Do you people with color in mind want to be crooked. I want to go to the comment area.

Let's take a look at my friend's girlfriend.

/**
 * @Author: buding
 * Girlfriends
 * 
 * @DateTime: 2020/6/8 8:52 afternoon
 */
public class Girl {
    // Likability
    private int favorability = 0;
    /**
     * Shopping
     */
    public void shop() {
        System.out.println("You go shopping with your girlfriend+30");
        // Favorability + 30
        favorability += 30;
        showFavorability();
    }
    /**
     * having dinner
     */
    public void eat() {
        System.out.println("You and your girlfriend go to see dinner together+30");
        favorability += 30;
        showFavorability();
    }
    /**
     * watch movie
     */
    public void watchMovie() {
        System.out.println("You go to the movies with your girlfriend. It's nice+30");
        favorability += 30;
        showFavorability();
    }
    /**
     * Hey, hey, hey
     */
    public void heiheihei() {
        if (favorability > 90) {
            System.out.println("Waiting for you in the evening heiheihei");
        } else {
            System.out.println("Police uncle!!!!! This is a pervert");
        }
    }
    private void showFavorability() {
        System.out.println("Your and your girlfriend's liking degree is:" + favorability);
    }
}

After watching the girlfriend above.


There are a lot of little friends who say, can we just do it?

Well, I don't know. Is the joke so funny? Isn't shopping good?

I don't understand you.

But here, if we want to have sex with our girlfriend. First of all, we need to achieve a certain degree of good will of more than 90.
So how can we get there?

We can go shopping, eat and watch movies with our girlfriend. In this way, the favorability will reach 100.
We can have a girlfriend.

ok, simple.


So let's start.

  public static void main(String[] args) {
        Girl girl = new Girl();
        // Shopping
        girl.shop();
        // having dinner
        girl.eat();
        // watch movie
        girl.watchMovie();
    }

We've been shopping with our girlfriends, eating cashews and watching love movies. Just when you want to open a room with your girlfriend to tell jokes.


Girlfriend suddenly said: people want to tell jokes in the presidential suite of a five-star hotel.

So you looked at your Alipay's only 150 yuan.
In a daze.


You look at your girlfriend and say, "baby, can you wait for me?"? I must tell you a joke in the presidential suite of a five-star hotel. But I don't have money now. I'm going to Beijing to move bricks. Make money with great effort,


Ten to ten years later, I'll take you to a five-star hotel to tell jokes.

Girlfriend said: OK, I'll wait for you.. You go. [crying

So you started to work for ten years

In the next ten years

You look at the 10000 yuan that you finally saved after ten years of moving bricks.

Today, I can finally go to the five-star hotel presidential suite with my girlfriend to tell jokes.


So you ask your girlfriend if you want to.

     Girl girl = new Girl();
     girl.heiheihei();

However, the answer you get is


oh, my God? Why? Why? Why is that? I've been carrying bricks for ten years. Why is she still reluctant to tell jokes with me. Mingming ~ Mingming we have all experienced so much.

Why? God tell me!!!

This is a golden light shining in front of you.

A white haired grandfather came to you.


"Young man, do you think your girlfriend has changed?"

"Yeah? Why? "

"Well, he's not your girlfriend anymore. Because you don't use a single example, every time you create a girlfriend, it's a different girlfriend. "

"What is a single case? How do I use a single case!!! Tell me! "


"Sao Nian, don't worry. Let's talk about it."

Start of text

What is singleton mode?

After watching the above tragedy, we know that in order to be able to have a good time with our girlfriend, we must use the single example.

If it's not practical, we should go shopping, eat and watch movies with our girlfriend first. Only then.

If we use single example, we can only accompany her to do it once, and then we can tell jokes with her at any time.

Are you happy? Excited?

So what is singleton?

The only way is to have only one girlfriend. And it can be called at any time.

"Pudding, pudding. I like to play sports with many people. "

So the simple definition of singleton pattern is: there is only one instance, and it provides a global calling method

Easy. It's not hard. So let's take a look at how to implement the singleton. There are several ways to implement singletons.

Five writing methods of single case mode

The following are several methods commonly used to implement a single example. I don't feel that there is an absolutely optimal method. As for which method is ultimately used, it depends on the requirements of the project.

ok, talk less nonsense. Let's have a look.

1. Lazy method

As the name suggests, laziness means that instances are created when they are used. "Laziness" means that instances are checked when they are used. If there are instances, they are returned. If not, they are created.

Advantages: easy to write and understand
Disadvantage: unsafe thread

/**
 * @Author: buding
 * Slovenly
 * @DateTime: 2020/6/8 12:45 afternoon
 */
public class Lhan {
    private static Lhan instance = null;
    // Privatization of construction methods to prevent external calls
    private Lhan() {
        System.out.println("Created Lhan");
    }
    // Use static to make external calls directly.
    public static Lhan getInstance() {
        // Judge whether there has been instantiation. If there is no instance, it will return the instantiated object directly
        if (instance == null) {
            instance = new Lhan();
        }
        return instance;
    }
}

2. Hungry Han method

It's also easy to understand from the name of starved Chinese style, which is "more frequent". Because the static keyword is used, the instance has been built during initialization. Whether you use it or not, you need to build it first.

Advantages: simple writing, no thread safety issues
Disadvantage: wasted memory space

public class Ehan {
    private static final Ehan instance = new Ehan();

    public Ehan() {
        System.out.println("Created Ehan");
    }

    public static Ehan getInstance() {
        return instance;
    }
}

2. Double check lock

Double check lock, also known as double check lock, integrates the advantages and disadvantages of lazy type and hungry type. In the above code implementation, the feature is that a layer of if condition judgment is added inside and outside the synchronized keyword, which not only ensures thread safety, but also improves execution efficiency and saves memory space compared with direct locking.
Remember to add the volatile keyword because instance = new DoubleCheck(); is not done in one step. Without volatile, multithreading is prone to the problem of instruction rearrangement.

Instruction rearrangement: a sequence of instructions formed after the sequence of instructions executed by a computer is compiled by a program compiler. Generally speaking, this sequence of instructions will output certain results to ensure that each execution has certain results. However, in general, in order to improve the efficiency of program execution, CPU and compiler will allow instruction optimization according to certain rules.

Advantage: no thread safety issues
Disadvantages: trouble writing

/**
 * @Author: buding
 * Double lock
 * @DateTime: 2020/6/8 1:01 afternoon
 */
public class DoubleCheck {

    private static volatile DoubleCheck instance = null;

    private DoubleCheck() {
        System.out.println("Created DoubleCheck");
    }

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

2. Static inner class

Static inner classes mainly make use of the characteristics of JVM itself. The static keyword is only executed once when the class is loaded, so it will not be created multiple times.

Advantages: simple writing without multithreading
Disadvantage: only applicable to static domain

/**
 * @Author: buding
 * Static inner class
 * @DateTime: 2020/6/8 1:04 afternoon
 */
public class StaticClass {


    private StaticClass() {
        System.out.println("Created StaticClass");
    }

    private static class Holder {
        private static StaticClass instance = new StaticClass();
    }

    public static StaticClass getInstance() {
        return Holder.instance;
    }
}

2. Enumeration

Enumeration is a relatively rare way of implementation. It also takes advantage of the characteristics of the JVM itself to prevent multiple instantiations.

Advantages: easy to write
Disadvantage: poor understanding, unable to pass initialization parameters

/**
 * @Author: Yu Ding
 * @DateTime: 2020/6/8 1:27 afternoon
 */
public enum Enums {
    INSTANCE;

    private EnumDemo enumDemo = new EnumDemo();

    public EnumDemo getEnumDemo() {
        return enumDemo;
    }
}

Postscript

After talking about these things with my friend, he also successfully wrote out the girlfriend of the singleton model.
And also successfully went to the five-star presidential suite with her to tell jokes.

The code is as follows

/**
 * @Author: buding
 * Single version of girlfriend (static internal class)
 * @DateTime: 2020/6/8 8:52 afternoon
 */

public class GirlSignleton {

    private static GirlSignleton instance;

    // Likability
    private int favorability = 0;

    private GirlSignleton() {
        shop();
        eat();
        watchMovie();
    }

    private static class Holder {
        private static GirlSignleton girlSignleton = new GirlSignleton();
    }

    public static GirlSignleton getInstance() {
        return Holder.girlSignleton;
    }

    /**
     * Shopping
     */
    public void shop() {
        System.out.println("You go shopping with your girlfriend+30");
        // Favorability + 30
        favorability += 30;
        showFavorability();
    }

    /**
     * having dinner
     */
    public void eat() {
        System.out.println("You and your girlfriend go to see dinner together+30");
        favorability += 30;
        showFavorability();
    }

    /**
     * watch movie
     */
    public void watchMovie() {
        System.out.println("You go to the movies with your girlfriend. It's nice+30");
        favorability += 40;
        showFavorability();
    }

    /**
     * Hey, hey, hey
     */
    public void heiheihei() {
        if (favorability > 90) {
            System.out.println("Waiting for you in the evening heiheihei");
        } else {
            System.out.println("Police uncle!!!!! This is a pervert");
        }
    }

    private void showFavorability() {
        System.out.println("Your and your girlfriend's liking degree is:" + favorability);
    }

}

ok, today's singleton pattern is here. Finally, we use the static inner class to implement the singleton girlfriend. Partners can try to write about their girlfriends in other ways. If you have any questions, please point out in the comment area. thank you 🙏

Tags: jvm Java less

Posted on Tue, 09 Jun 2020 02:01:18 -0400 by rkm11