简单单利模式

来源:互联网 发布:我的世界java内存不足 编辑:程序博客网 时间:2024/06/14 11:01

懒汉式

//懒汉式单利模式
public class SingleInstance {
    //类对象为静态
    private static SingleInstance sInstance = null;
    //构造函数私有
    private SingleInstance(){};
    public static SingleInstance getInstance(){
        //不为空时,才创建对象,创建一次之后,获取多少次,都为同一个
        if(sInstance==null){
            sInstance = new SingleInstance();
        }
        return sInstance;
    }
}

饿汉式

//饿汉式单利模式
public class SingleInstanceE {
     //设立静态变量,直接创建实例  
    private static SingleInstanceE singleInstanceE = new SingleInstanceE();  
    //私有化构造函数
    private SingleInstanceE(){};
    public static SingleInstanceE getInstance(){
        return singleInstanceE;
        
    }
    
}

原创粉丝点击