创建者设计模式之单例模式
- 1.饿汉式
- 2.懒汉式
- 3.双重检测锁(不推荐,可能会有bug)
- 4.静态内部类
- 5.枚举
//饿汉式 -- 常用 速度快 但是无法延时加载
class Sigleton1 {
private static final Sigleton1 Instance = new Sigleton1(); //由于static的原因,不会有多线程下的问题
private Sigleton1(){
}
public static Sigleton1 getInstance(){
return Instance;
}
}
//懒汉式 -- 不常用 可以实现延时加载,但是由于要使用锁,所以速度很慢。
class Sigleton2{
private static Sigleton2 Instance;
private Sigleton2(){
}
public static synchronized Sigleton2 getInstance(){
if(Instance == null){
Instance = new Sigleton2();
}
return Instance;
}
}
//双重检测锁模式 -- 不用 可以减少懒汉式所造成的时间过长
class Sigleton3{
private static Sigleton3 Instance;
private Sigleton3(){
}
public static Sigleton3 getInstance(){
if (Instance == null){
synchronized (Sigleton3.class){
if (Instance == null){
Instance = new Sigleton3();
}
}
}
return Instance;
}
}
//静态内部类 --常用 可以延时加载 速度快
class Sigleton4{
//静态内部类只有在调用时才会初始化
private static class Sigleton{
private static final Sigleton Instance = new Sigleton();
Sigleton(){
}
}
public static Sigleton getInstance(){
return Sigleton.Instance;
}
}
//枚举--天然单例 不可以延时加载 速度快 可以防止反射
enum Sigleton5{
INSTANCE();
Sigleton5(){
}
}