单例模式
1.单例类只能有一个实例。
2.单例类必须自己创建自己的唯一实例。(所以需要构造方法私有化)
3.单例类必须给所有其他对象提供这一实例。
单例模式的几种实现方式
一、饿汉式
优点:没有加锁,执行效率会提高
缺点:类加载进行初始化时就会创建实例,如果没有使用到这个实例造成了空间的浪费
public class SingletonOne {
private static SingletonOne singletonOne = new SingletonOne();
private SingletonOne() {
System.out.println("构造方法私有化");
}
public static SingletonOne getSingletonOne() {
return singletonOne;
}
}
二、懒汉式,线程不安全
优点:使用时才会创建实例
缺点:用时间换取空间,当使用该类时创建实例,会使得使用时等待的时间稍长。并且由于singletonTwo==null 造成了这个方法不是线程安全的,可能造成两个线程同时实例化该类,造成线程不安全的现象,也不再满足一个类只有一个实例的单例要求。
public class SingletonTwo {
private static SingletonTwo singletonTwo;
private SingletonTwo() {
}
public static SingletonTwo getSingletonTwo() {
if (singletonTwo == null) {
singletonTwo = new SingletonTwo();
}
return singletonTwo;
}
}
三、懒汉式,线程安全
优点:线程安全,什么时候使用什么时候创建实例
缺点:在调用类时创建实例造成了调用时间延长
public class SingletonFour {
private static SingletonFour singletonFour;
private SingletonFour() {
}
public static SingletonFour getSingletonTwo() {
if (singletonFour == null) {
synchronized (SingletonFour.class) {
if (singletonFour == null) {
singletonFour = new SingletonFour();
}
}
}
return singletonFour;
}
}
四、静态内部类单例模式
此种方法线程安全,并且是在调用getSingletonThree() 这个方法时才会对内部类(Inner)进行初始化并创建SingletonThree实例,不会造成空间浪费。
public class SingletonThree {
private SingletonThree() {
}
public static SingletonThree getSingletonThree() {
return Inner.singletonThree;
}
private static class Inner {
private static SingletonThree singletonThree = new SingletonThree();
}
}
原文:https://www.cnblogs.com/lxxyd/p/12125671.html