Understand the Singleton pattern by comparing Java and JavaScript code

Introduction

Details and other patterns will be written in ** Understanding design patterns by comparing implementations in JavaScript and Java **.

Singleton pattern

Software usually creates or prepares multiple instances from a class However, there are times when "I only create one instance of this class and I don't want to." Like the legendary sword in RPGs If you get many legendary swords in one game, online game, etc., the value will decrease.

A putter that guarantees that only one such instance exists is called the ** Singleton pattern **.

Implementation example in Java

Class diagram

The constructor is private so that if you write `new Singleton ()`, you will get an error. Singleton.png

code

Main.java


public class Main {
    public static void main(String[] args) {
        System.out.println("Strat.");
        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();
        if (obj1 == obj2) {
            System.out.println("obj1 and ojb2 are the same instance.");
        } else {
            System.out.println("obj1 and obj2 are not the same instance.");
        }
        System.out.println("End.");
        //I get an error when I uncomment the following
        // Singleton obj3 = new Singleton();
    }
}

Singleton.java


public class Singleton {
    private static Singleton singleton = new Singleton();

    private Singleton() {
        System.out.println("You have created an instance.");
    }
    public static Singleton getInstance() {
        return singleton;
    }
}

** Instance generation timing **

I think the execution result will be as follows

Start.
You have created an instance.
obj1 and obj2 are the same instance.
End.

As you can see above, you can see that the instance was created the first time the getInstance method was called. The Singleton class is loaded when the getInstance static method is called.

Implementation example in JavaScript

code

index.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Singleton</title>
    <script src="Main.js"></script>
    <script src="Singleton.js"></script>
</head>
<body>
    
</body>
</html>

Main.js


var MAIN = {};

MAIN.init = function() {
    console.log("Start.");
    /**
     *The book said the following, but I changed it to make it easier to compare
     * var obj1 = SINGLETON.singleton
     * var obj2 = SINGLETON.singleton
     */
    var obj1 = SINGLETON.singleton.getInstance();
    var obj2 = SINGLETON.singleton.getInstance();
    if (obj1 === obj2) {
        console.log("obj1 and obj2 are the same instance.");
    } else {
        console.log("obj1 and obj2 are not the same instance.");
    }
    console.log("End.");
};

window.addEventListener("load", MAIN.init);

Singleton.js


var SINGLETON = {};

SINGLETON.singleton = (function() {
    var instance;

    function init() {
        console.log("You have created an instance.");
        var privateVariable = "I am also private";
        function privateMethod() {
            console.log("I am private");
        }

        return {
            publicProperty: "I am also public",
            publicMethod: function() {
                console.log("The public can ses me!");
            }
        };
    };

    return {
        getInstance: function() {
            if (!instance) {
                instance = init();
            }

            return instance;
        }
    };
})();

Characters in the Singleton pattern

** The role of Singleton **

Has a static method to get only one instance This method always returns the same instance

Singleton class diagram

Singleton.png

Singleton pattern need

Guarantee when you only want to create one instance as described above In addition, delayed execution is important for singletons. Doesn't consume memory unless a static instance is needed as a reason In the case of C ++, the order of dynamic initialization is unpredictable, so using a singleton has the advantage that the programmer can decide the timing himself. In addition to wanting to make only one, use it for things that do not make sense even if you can make two or more

Example of use When you want to use a class like a global variable

Related patterns

reference

[Introduction to Design Patterns Learned in the Enhanced and Revised Java Language](https://www.amazon.co.jp/%E5%A2%97%E8%A3%9C%E6%94%B9%E8%A8%82% E7% 89% 88Java% E8% A8% 80% E8% AA% 9E% E3% 81% A7% E5% AD% A6% E3% 81% B6% E3% 83% 87% E3% 82% B6% E3% 82% A4% E3% 83% B3% E3% 83% 91% E3% 82% BF% E3% 83% BC% E3% 83% B3% E5% 85% A5% E9% 96% 80-% E7% B5 % 90% E5% 9F% 8E-% E6% B5% A9 / dp / 4797327030) JavaScript design pattern

Recommended Posts

Understand the Singleton pattern by comparing Java and JavaScript code
Understand the Iterator pattern by comparing Java and JavaScript code
[Java] Singleton pattern
Java and JavaScript
[Java] Understand the difference between List and Set
Understand bugs by implementing and analyzing them (1) Deadlock (Java)
Java classes and instances to understand in the figure
I didn't understand the behavior of Java Scanner and .nextLine ().
Difference between Java and JavaScript (how to find the average)
[For beginners] About the JavaScript syntax explained by Java Gold
Correct the character code in Java and read from the URL
[Rails] Understand migration up and down by comparing with change
[Java] Appropriate introduction by the people of Tempa Java Part 0 (Code rules)
Guess the character code in Java
[java8] To understand the Stream API
Java 15 implementation and VS Code preferences
Understand the difference between each_with_index and each.with_index
Java 9 new features and sample code
Arbitrary string creation code by Java
Java pass by value and pass by reference
The road from JavaScript to Java
By checking the operation of Java on linux, I was able to understand compilation and hierarchical understanding.
Web application structure by Java and processing flow in the presentation layer
A collection of phrases that impresses the "different feeling" of Java and JavaScript
Beginners can see the Devise code and understand the mechanism softly [registrations new]
Understand the difference between int and Integer and BigInteger in java and float and double
Java reference to understand in the figure
Link Java and C ++ code with SWIG
Let's try WebSocket with Java and javascript!
[Java 7] Divide the Java list and execute the process
Execute Java code stored on the clipboard.
The story received by Java SE11 silver
I studied the State pattern and the Strategy pattern
[Java8] Search the directory and get the file
Page number logic and reference code (java)
Java vs. JavaScript: What ’s the Difference?
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
Build Apache and Tomcat environment with Docker. By the way, Maven & Java cooperation
Parse the date and time string formatted by the C asctime function in Java