Java单例设计模式

核心是私有构造方法。

class Singleton{
    private static Singleton obj = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return obj;
    }
    public String toString(){
        return "Hello world!";
    }
}


public class SingletonDemo {
    public static void main(String[] args) {
        Singleton o = Singleton.getInstance();
        System.out.println(o);        
    }
}
 

 

posted @ 2015-12-09 16:04  finalboss1987  阅读(274)  评论(0编辑  收藏  举报