单例模式是指该类只能有一个实例,并且该实例只有由该类自己创建。
在jdk中,Runtime就是一个很典型的单例模式。
单例设计模式一般有两种实现方式:
饿汉模式
饿汉模式是指该类在加载的过程中,就已经生成对应的实例,Runtime类就是基于饿汉模式实现的单例,因为饿汉模式是在类加载的过程中产生实例,因此,饿汉模式本身就是线程安全的,可以使用在多线程情况下。
实现方式:
public class Hungry {
private static Hungry hungry = new Hungry();
private Hungry() {
}
public static Hungry getHungry() {
return hungry;
}
public void display() {
System.out.println("this is Hungry");
}
}
懒汉模式
懒汉模式,顾名思义,在使用的时候才去创建对应的实例,因此,懒汉模式在多线程的场景中,需要使用volatile或者synchronized来保证线程安全。
public class Lazy {
private Lazy() {
}
private static volatile Lazy lazy;
public static synchronized Lazy getLazy() {
if (lazy == null) {
lazy = new Lazy();
}
return lazy;
}
public void display() {
System.out.println("this is Lazy");
}
}
测试代码:
public class Singleton {
public static void main(String agrs[]) {
Hungry.getHungry().display();
Lazy.getLazy().display();
}
}
输出:
this is Hungry
this is Lazy