单利模式只生成一个实例,减少系统性能开销,生成一个单利对象后,永久驻留内存
1.饿汉式
public class SingletonClass {
private static SingletonClass instanceClass = new SingletonClass();
private SingletonClass() {
}
public static SingletonClass shareInstance() {
return instanceClass;
}
}
2.懒汉式
public class SingletonClass {
private static SingletonClass instanceClass = null;
private SingletonClass() {
}
//方法一
public static synchronized SingletonClass shareInstance() {
if (instanceClass == null) {
instanceClass = new SingletonClass();
}
return instanceClass;
}
//方法二
public static SingletonClass shareInstance() {
if (instanceClass == null) {
synchronized(SingletonClass.class){
if (instanceClass == null) {
instanceClass = new SingletonClass();
}
}
}
return instanceClass;
}
}
区别:
饿汉式编译之后在内存中就存在,线程安全
懒汉式延时对象创建,非线程安全
网友评论