标签:
本例中通过将构造函数私有化的方式将实例化对象的代码放到类内部的静态函数中,从而实现单例设计模式。
class Singleton { static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return Singleton.instance; } public void func() { System.out.println("Hi there, this is a singleton demo."); } } public class Hello { public static void main(String[] args) { Singleton ins_1 = Singleton.getInstance(); Singleton ins_2 = Singleton.getInstance(); Singleton ins_3 = Singleton.getInstance(); ins_1.func(); ins_2.func(); ins_3.func(); } }
标签:
原文地址:http://www.cnblogs.com/kuillldan/p/5571989.html