单列模式分为两种:
饿汉式:
package util;
public class Single {
public static Single s = new Single();
private Single(){
}
public static Single getSingle(){
return s;
}
}
懒汉式:
package util;
public class Single {
public static Single s = null;
private Single(){
}
public static Single getSingle(){
if(s == null){
synchronized (Single.class) {
if(s == null){
s = new Single();
}
}
}
return s;
}
}
对于懒汉式存在多线程安全问题,
懒汉式有点是懒加载.
synchronized(对象)对于静态方法(static)来说,他的对象是在堆内存中的方法区中,对象是.class文件.