单利模式应该是开发中用的最多的一种。
//饿汉式 class Single { private Single(){}; private static Single s = new Single(); public static Single getInstance() { //return new Single(); // 这样其实是每一次都创建一个新对象,不要混淆 return s; } } class Test { public static void main(String[] args) { Single ss = Single.getInstance(); } }
方式二 :懒汉式
//懒汉式 class Single { private Single(){}; private static Single s = null; public static Single getInstance() { if(s == null) s = new Single(); return s; } } classTest { public static void main(String[] args) { Single ss = Single.getInstance(); } }
小结:
//懒汉式+多线程 class Single { private Single(){}; private static Single s = null; public static Single getInstance() { if (s==null) { synchronized(Single.class) { if (s==null) { s = new Single(); } } } } } class Test { public static void main(String[] args) { Single ss = Single.getInstance(); new Thread(ss).start(); new Thread(ss).start(); } }
原文:http://www.cnblogs.com/weiguannan/p/4456160.html