单例-设计模式(Design Pattern)
设计模式基础知识
基础概念 . . . .简而言之,就是套路二字.是一套反复被使用,多数人知晓的,经过分类编目,代码设计经验的总结.对待不同情况,可以使用的最优解.还是古人云的好啊 . . . . .自古深情留不住,唯有套路得人心!作用 . . . . 实用设计模式不仅仅可以提高代码重用度,代码更容易理解,保证代码的可靠性.使用场景 . . . . 工具类,配置文件,线程池,缓存,日志等 单例设计模式—饿汉式
代码参考
public class Singleton {
private Singleton() {
}
private static Singleton instance
= new Singleton();
public static Singleton
getInstance(){
return instance
;
}
}
单例设计模式—懒汉式
代码参考
public class SingletonLazy {
private SingletonLazy() {
}
private static SingletonLazy instance
;
public static SingletonLazy
getInstance(){
if(instance
== null){
instance
= new SingletonLazy();
}
return instance
;
}
}
单例设计模式—测试
代码参考
public class SingletonTest {
public static void main(String
[] args
) {
Singleton s0
= Singleton
.getInstance();
Singleton s1
= Singleton
.getInstance();
System
.out
.println(s0
);
System
.out
.println(s1
);
System
.out
.println("-------------------------");
SingletonLazy s2
= SingletonLazy
.getInstance();
SingletonLazy s3
= SingletonLazy
.getInstance();
System
.out
.println(s2
);
System
.out
.println(s3
);
}
}
单例设计模式—总结
饿汉式,是加载类时比较慢,但运行时获取的对象速度比较快,线程安全.懒汉式加载类时比较快,但运行获取对象的速度比较慢,线程不安全