单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。
这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
单例类只能有一个实例。
单例类必须自己创建自己的唯一实例。
单例类必须给所有其他对象提供这一实例。
1.单例模式——线程安全的饿汉模式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
2.单例模式——线程安全的懒汉模式
public class Singleton {
private static Singleton instance = null;
private Singleton(){
}
//如果不加synchronized,则是线程不安全的
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
3.单例模式——线程安全的懒汉模式改进版(双重检查锁)
/**
*双重锁:为了减少同步的开销
*/
public class Singleton{
// 静态可见的实例
private static volatile Singleton instance = null;
// 无参构造器
private Singleton(){
}
public Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
4.单例模式——私有的内部工厂类(线程安全)
public class Singleton {
private Singleton(){
}
public static Singleton getInstance(){
return SingletonFactory.Instance;
}
private static class SingletonFactory{
private static Singleton Instance = new Singleton();
}
}
//内部类也可以换成内部接口,但是工厂类变量的作用域需为public