单例模式
单例模式
饿汉式,在类初始化时就创建好了单例对象
public class Design {
private Design(){
System.out.println("私有方法调用");
}
private static final Design singleton1= new Design();
public static Design get(){
return singleton1;
}
public static void jk(){
System.out.println("kkk");
}
}
懒汉式,只有在调用的时候才创建对象
public class Design2 {
private Design2(){
System.out.println("design2");
}
private static Design2 singleton2 = null;
public static Design2 getInstance(){
if(singleton2 == null){
synchronized (Design2.class){
if(singleton2 == null){
singleton2 = new Design2();
}
}
}
return singleton2;
}
public static void jk(){
System.out.println("jk");
}
}