Here is a summary of the ** Singleton pattern ** in the GoF design pattern.
--Singleton means ** a set with only one element **. --The Singleton pattern is a ** method that guarantees that there is only one instance **. --For example, a class that expresses the system settings, a class that expresses the window system, and so on. --In the GoF design pattern, it is classified as ** Design pattern for generation **.
A program that creates a singleton instance.
A class that returns only one instance. The constructor for the Singleton class is private. This is to prohibit calling the constructor from outside the Singleton class.
Singleton.cs
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;
}
}
This class performs the main processing.
Main.cs
public class Main {
public static void main(String[] args) {
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
if (obj1 == obj2) {
System.out.println("obj1 and obj2 are the same instance.");
} else {
System.out.println("obj1 and obj2 are not the same instance.");
}
}
}
You have created an instance.
obj1 and obj2 are the same instance.
The Singleton pattern puts a limit on the number of instances. If you have multiple instances, the instances can interact with each other and create unexpected bugs. However, if you guarantee that you have only one instance, you can program with that prerequisite.
-** GoF design pattern summary **
This article and sample program were created based on the following books.
-** Introduction to design patterns learned in Java language **
It was very easy to understand and I learned a lot. Thank you. The detailed explanations of design patterns and sample programs are written, so please take a look at the books as well.
Recommended Posts