简介
本篇只是简单介绍单列模式,主要是让初学者理解单列模式,各种加锁、多实现、业务场景待以后补充。
具体实现
关键字: 只产生一个实例,构造器私有化。
构造器私有化(private),是为了禁止Singleton类外部调用构造函数。如果从Singleton类以外的代码中调用构造函数
(new Singleton),就会出现编译错误。Singleton模式在于确保任何情况下都只生成一个实例。
1.1.饿汉模式:不管你需不需要我都实例化。
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {
System.out.println("生成了一个实例");
}
public static Singleton getInstance() {
return singleton;
}
}
测试类:
public class SingletonMain {
public static void main(String[] args) {
//会编译出错,构造函数Singleton()不可见(私有)
//Singleton singleton = new Singleton();
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
if(s1 == s2) {
System.out.println("s1和s2是相同的实例");
}else {
System.out.println("s1和s2是不同的实例");
}
}
1.2.懒汉模式:只有你需要的时候我才给
public class SingletonLazy {
private static SingletonLazy singletonLazy = null;
private SingletonLazy() {
System.out.println("生成了一个实例");
slowdown();
}
//线程不安全
// public static SingletonLazy getInstance() {
// if(singletonLazy == null) {
// singletonLazy = new SingletonLazy();
// }
// return singletonLazy;
// }
//线程安全,但锁的是方法,粗粒度锁
public static synchronized SingletonLazy getInstance() {
if(singletonLazy == null) {
singletonLazy = new SingletonLazy();
}
return singletonLazy;
}
//先调用的停止一秒,多线程测试
private void slowdown() {
try {
//sleep使当前线程让出cpu,但如果在锁内,它并不会让出锁。
Thread.sleep(1000);
}catch (InterruptedException e) {
}
}
}