Singleton pattern in Java

Introduction

Introducing the design patterns of [GoF](https://ja.wikipedia.org/wiki/Gang of for _ (Information Engineering)) ["Introduction to Design Patterns Learned in the Augmented and Revised Java Language"]( https://www.amazon.co.jp/ Augmented and revised edition Introduction to design patterns learned in Java language-Hiroshi Yuki / dp / 4797327030 / ref = pd_lpo_sbs_14_t_0? _ Encoding = UTF8 & psc = 1 & refRID = 2ZE4GPYNN55JGDR5QMHP) I will summarize about.

Singleton pattern

What is Singleton

Translated into Japanese, it is a single card of playing cards, which means that there is only one card in the whole set. For this reason, the ** pattern that guarantees that there is only one instance in the entire system ** is called the ** Singleton pattern **.

Character

The classes that appear in the class diagram below are used in the Singleton pattern. That said, there is only one of the Singleton classes. image.png

Concrete example

As a concrete example, the explanation will be based on the singleton class and the execution class.

Implementation class

-** Singleton class **

Singleton.java


package singleton;

public class Singleton {
	// 1.static field(Class variables)Define singleton as
	private static Singleton singleton = new Singleton();

	// 2.private constructor
	private Singleton() {
		System.out.println("Successful instance creation");
	}

	// 3.Return singleton instance
	public static Singleton getInstance() {
		return singleton;
	}
}

The points are the following three points. ** 1. ** singleton is defined as a private class variable. ** 2. ** The constructor is private and cannot be called by other classes. (cannot new) ** 3. ** Defines a getInstance () method that returns a singleton instance.

I will give a supplementary explanation. First, the external class calls the public getInstance () method. When it is called for the first time at that time, the Singleton class is initialized, and the Singleton class is instantiated only once at that time. After that, when the getInstance () method is called, the instance of the Singleton class that has already been created will be returned. In the constructor, the output is made so that you can see that the instance was created successfully, but it is usually unnecessary.

Execution class

-** Main class ** Call the getInstance () method twice to make sure you are getting the same instance.

Main.java


package singleton;

public class Main {
    public static void main(String[] args) {
        System.out.println("***Start execution class***");
        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();
        if (obj1 == obj2) {
            System.out.println("obj1 is obj2");
        } else {
            System.out.println("obj1 is not obj2");
        }
        System.out.println("***End of execution class***");
    }
}

Execution result

The result of executing Main.java is as follows. ʻObj1 is obj2` is output, and you can confirm that you can get the same instance.

Execution result


***Start execution class***
Successful instance creation
obj1 is obj2
***End of execution class***

merit

By using the Singleton pattern, you can be assured that there is only one instance in your entire system. By doing this, you can prevent multiple instances from getting entangled and causing unexpected bugs.

Summary

You learned about the Singleton pattern, which guarantees that there is only one instance. The sample code is uploaded below, so please refer to it if you like.

-Singleton sample code

In addition, other design patterns are summarized below, so please refer to them as well.

-[Updated from time to time] Summary of design patterns in Java

References

-[Introduction to Design Patterns Learned in the Augmented and Revised Java Language](https://www.amazon.co.jp/ Introduction to Design Patterns Learned in the Augmented and Revised Java Language-Hiroshi Yuki / dp / 4797327030 / ref = pd_lpo_sbs_14_t_0? _Encoding = UTF8 & psc = 1 & refRID = 2ZE4GPYNN55JGDR5QMHP)

Recommended Posts

Singleton pattern in Java
Facade pattern in Java
Flyweight pattern in Java
Singleton pattern in Python
Observer pattern in Java
Iterator pattern in Java
Decorator pattern in Java
Prototype pattern in Java
Proxy pattern in Java
Template Method pattern in Java
Implement the Singleton pattern in Python
Chain of Responsibility pattern in Java
Design Pattern #Singleton
Linux permissions in Java
Use DataFrame in Java
Visitor pattern in Python
I wrote a design pattern in kotlin Singleton edition
Summary of Singleton patterns introductory design patterns learned in Java language
Implement Table Driven Test in Java
Detect and process signals in Java.
Implemented bubble sort in Java (BubbleSort)
GoF java design pattern rough summary
Overlapping regular expressions in Python and Java
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
[Gang of Four] Design pattern learning --Singleton
Learn the design pattern "Flyweight" in Python
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Express Python yield in JavaScript or Java
Apply Google Java Style formatter in IntelliJ
Learn the design pattern "Command" in Python
Differences in syntax between Python and Java
Get mail using Gmail API in Java
Learn the design pattern "Visitor" in Python
Learn the design pattern "Bridge" in Python
Learn the design pattern "Mediator" in Python
Learn the design pattern "Decorator" in Python
Learn the design pattern "Iterator" in Python
Learn the design pattern "Strategy" in Python
Learn the design pattern "Composite" in Python
Learn the design pattern "Singleton" with Python
Learn the design pattern "State" in Python
Let's run a Bash script in Java
Learn the design pattern "Adapter" in Python