单例模式

单例模式

只需要一个实例的场合,可以使用单例模式,如何日志处理,缓存,连接池,读取配置文件等场合。

饿汉模式

加载类时,就实例化

public class SingleTon{
    //1.将构造方法私有化,不允许外部直接创建对象
    private Singleton(){
    
    }
    //2.创建类的唯一实例,使用private static修饰
    private static Singleton instance = new Singleton();
    
    //3.提供一个用于获取实例的方法,使用public static修饰
    public static Singleton getInstance(){
        return instance;
    }
}

懒汉模式

需要类时,再进行实例化

public class SingleTon{
    //1.将构造方法私有化,不允许外部直接创建对象
    private Singleton(){
    
    }
    //2.创建类的唯一实例,使用private static修饰
    private static Singleton instance ; 
    //3.提供一个用于获取实例的方法,使用public static修饰
    public static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton;
        }
        return instance;
    }
}

你可能感兴趣的:(单例模式)