登记式单例模式
package comhellojava;import java.util.HashMap;import java.util.Map;/** * @function 登记式单例模式 类似于spring里面的用法,将类名注册,下次从里面直接获取 * @author ylchou * @time 2012/08/28 * */public class Singleton { private static Map<String, Singleton> map = new HashMap<String,Singleton>(); static{ Singleton singleton = new Singleton(); System.out.println("--------"+singleton.getClass().getName()); //把singleton实例 put 进 comhellojava.Singleton map.put(singleton.getClass().getName(), singleton); } //protected 构造器// protected Singleton(){// } private Singleton(){ } //静态工厂方法 返回此类唯一的实例 public static Singleton getInstance(String name){ if(name == null){ name = Singleton.class.getName(); System.out.println("if name is null,->name=" + name); } if(map.get(name) == null){ try { map.put(name, (Singleton) Class.forName(name).newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return map.get(name); } public String about() { return "登记式单例模式"; } public static void main(String[] args) { Singleton s = Singleton.getInstance(null); Singleton s2 = Singleton.getInstance(null); System.out.println(s); System.out.println(s2); System.out.println(s.about()); }}