对象的单例模式--饿汉式

今天面试题目: 设计一个类让我们只能生成该类的一个实例

回来总结了一下:

        1普通法

        2饿汉式

public sealed class Singleton1{
    private Singleton(){
    
    }
    private static Singleton1 instance=null;
    public static Singleton1 Instance{
        get
        {
            if (instance==null){
                instance=new Singleton1();
            return incetance;
            }    
        }
    }
}


//推荐利用静态构造函数:

public sealed class Singleton2{
    private Singleton2(){
        
    }
    private static Singleton2 instance = new Singleton2();
    public static Singleton2 Instance{
    get{
        return instance;
        }
    }
}

//饿汉type

public class t {
    private static t a=new t();
    private  t(){
        
    }
    public static t getit(){
        return a;
    } 
    
}

希望一切顺利

posted @ 2017-03-19 12:07  NHZ-M  阅读(149)  评论(0编辑  收藏  举报