public class Test01Singleton {
@Test
public static void main(String[] args) {
Singleton1 a = Singleton1.getInstance();
Singleton1 b = Singleton1.getInstance();
Singleton2 c = Singleton2.getInstance();
Singleton2 d = Singleton2.getInstance();
System.out.println((a==b)+" "+(c==d));//结果为true则代表应用的是同一对象
}
}
//饿汉式
class Singleton1{
private Singleton1(){};
private static Singleton1 instance1 = new Singleton1();//加静态是因为要被静态调用
public static Singleton1 getInstance(){
return instance1;
}
}
//懒汉式
class Singleton2{
private Singleton2(){};
private static Singleton2 instance2 = null;
public static Singleton2 getInstance(){
if(instance2 == null){
instance2 = new Singleton2();
}
return instance2;
}
}
思路:
1,首先把类的构造方法给私有化
2,创建一个静态的对象(饿汉式),懒汉式是创建一个引用对象赋值为null;
3.创建一个公开的静态的get方法,返回值为此类的对象(饿汉式)
4.懒汉式判断有没有这个对象(是否为null),有就直接return对象,没有就创建对象再返回