这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象
要点:
- 1、单例类只能有一个实例。
- 2、单例类必须自己创建自己的唯一实例。
- 3、单例类必须给所有其他对象提供这一实例。
1、饿汉模式
public class Singleton{
private static Singleton newInstance= new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return newInstance;
}
}
2、懒汉模式(线程不安全)
public class Singleton{
private static Singleton newInstance = null;
private Singleton(){}
public static Singleton getInstance(){
if(newInstance==null)
newInstance = new Singleton();
return newInstance;
}
}
3、懒汉模式(线程安全)
public class Singleton{
private static Singleton newInstance = null
private Singleton(){}
public static synchronized Singleton getInstance(){
if(newInstance == null)
newInstance = new Singleton();
return newInstance;
}
}
4、双重校验锁
public class Singleton{
private static volatile Singleton newInstance = null;
private Singleton(){}
public static Singleton getInstance(){
if(newInstance == null){
synchronized(Singleton.class){
if(newInstance == nul){
newInstance = new Singleton();
}
}
}
return newInstance;
}
}
5、静态内部类
public class Singleton{
private static class NewInstance{
private static Singleton newInstance = new Singleton();
}
private Singleton(){}
public static Singletion getInstance(){
return NewInstance.newInstance;
}
}