【一】设计一个类,我们只能生成该类的一个实例。

设计一个类,我们只能生成该类的一个实例。

其实就是单利模式的实现:

public class Singleton
{
    private Singleton(){ }

    public static Singleton getInstance()
    {
        return Singletonholder.instance;
    }

    //在第一次被引用时被加载
    private static class Singletonholder
    {
        private static Singleton instance = new Singleton();
    }

    public static void main(String args[])
    {
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance == instance2);
    }
}
posted @ 2018-05-30 10:12  西北野狼  阅读(472)  评论(0编辑  收藏  举报