Design pattern-Singleton pattern

What is the Singleton pattern?

Singleton literally means singleton, which means that this class has only one instance object anyway, and you cannot create multiple new instances of this class.

Application scenarios

  • Want to make sure there is absolutely only 1 instance under any circumstances
  • Want to show "only one instance exists" in the program

For example, when writing a Java web program, use some global configurations set by the framework. You have to ensure that the configuration is the same wherever you call it, rather than calling it differently in each place. In that case, the global configuration will be invalid, which will lead to program confusion and it will be difficult to find errors. .
Of course, you don't have to use the Singleton mode, but you must always be careful to prevent yourself from creating multiple new objects. So it is more worry-free to use design patterns.

Singleton pattern - UML diagram

Insert image description here

The meaning of this UML diagram is to declare a static private variable singleton in this Singleton class.
Then declare the constructor as private, so that you cannot create a new class outside the class.
To obtain an instance of this class, an external class can only obtain the static variable singleton in the class through getInstance.
The specific code is as follows:

Code

public class Singleton{
    
    
//静态私有变量
private static Singleton singleton = new Singleton();
//私有构造方法
private Singleton(){
    
     
System.out.println("生成了一个实例!!!");
}
//外部类通过Singleton.getInstance()获取这个类的对象。
public static Singleton getInstance(){
    
    
return singleton;}
}

Then you can test it through the Main function:

public class Main{
    
    
	public static void main(String[] args)
	{
    
    
		System.out.println("Strat.");
		Singleton s1 = Singleton.getInstance();
		Singleton s2 = Singleton.getInstance();
		if(s1==s2)
		System.out.println("true");
		else
		System.out.println("false");
		System.out.println("End.");
	}
}

Guess you like

Origin blog.csdn.net/qq_23128065/article/details/90604461