单例设计模式
1.使用单例设计模式有什么好处呢?
答:1.1 控制资源的使用,通过线程同步来控制资源的并发访问
1.2 控制实例产生是数量,达到节约资源的目的
1.3 作为通信媒介使用,也就是数据共享,它可以在不建立直接关联的条件下,让多个不相关的两个线程或者进程之间通信
2.单例设计模式的两种格式:
(一)第一种:懒汉式
public class Singleton {
private static Singleton singleton = null;
private Singleton() {
}
private synchronized static Singleton getInstance() {
if(singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
(二)第二种:恶汉式
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {
}
private Singleton getInstance() {
return singleton;
}
}