Java单例
/**
* @Author: DengJia
* @Date: 2023/3/22
* @Description: 单例
*/
public class Singleton {
public static void main(String[] args) {
System.out.println(HungrySingleton.getSingleton());
System.out.println(LazySingleton.getSingleton());
System.out.println(StaticInnerSingleton.getSingleton());
}
}
/**
* 饿汉式单例
*/
class HungrySingleton {
private HungrySingleton() {
}
private static HungrySingleton singleton = new HungrySingleton();
public static HungrySingleton getSingleton() {
return singleton;
}
}
/**
* 懒汉式单例
*/
class LazySingleton {
private LazySingleton() {
}
private static LazySingleton singleton = null;
public static synchronized LazySingleton getSingleton() {
if (singleton == null) {
singleton = new LazySingleton();
}
return singleton;
}
}
/**
* 静态内部类实现单例
*/
class StaticInnerSingleton {
private StaticInnerSingleton() {
}
private static StaticInnerSingleton singleton;
private static class SingletonHandler {
private static final StaticInnerSingleton singleton = new StaticInnerSingleton();
}
public static StaticInnerSingleton getSingleton() {
return SingletonHandler.singleton;
}
}
DJOSIMON