单例模式的意思就是只有一个实例。
单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
这个类称为单例类。
solution1:
solution2:
solution3:
Test:
result:
单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
这个类称为单例类。
solution1:
public class Singleton1{
private Singleton1(){}
private static Singleton1 s1;
public static Singleton1 getInstance(){
if(s1==null){
s1=new Singleton1();
}
return s1;
}
}
solution2:
solution3:
Test:
public class Test {
public static void main (String [] args)throws Exception{
Singleton1 s1A= Singleton1.getInstance();
Singleton1 s1B=Singleton1.getInstance();
System.out.println(s1A==s1B);
}
}
result:
true
true
true