单例设计模式,就是保证只有一个实例。
1.饿汉式单例
public class Singleton{
//1.私有化构造方法 private Singleton() {}
//2.定义一个静态的本类属性 private static Student s = new Student();
//3.提供一个静态方法,返回唯一的实例
public static Student getInstance() {
return s;
}
}
2.懒汉式单例
public class Singleton {
//1、私有化构造方法 private Singleton() {}
//2、定义一个静态的本类属性
private static Singleton s;
//3、提供一个静态方法,返回唯一的实例
public static Singleton getInstance() {
if(s == null) { s = new Singleton();
}
return s;
}
}
饿汉式单例是线程安全的,懒汉式单例是线程不安全的,使用同步锁可以保证线程安全。
public static Student2 getInstance() {
if (s == null) {
synchronized (Student2.class) {
if (s == null) {
s = new Student2();
}
}
}
return s;
}