再举个例子,集合中的 set 中不能包含重复的元素,添加到set里的对象必须是唯一的,假如重复的值添加到 set,它只接受一个实例。JDK中正式运用了Singleton模式来实现 set 的这一特性,大家可以查看java.util.Collections里的内部静态类SingletonSet的原代码。其实Singleton是最简单但也是应用最广泛的模式之一,在 JDK 中随处可见。
public class Singleton { private static Singleton s; private Singleton() { }; /** * Class method to access the singleton instance of the class。 */ public static Singleton getInstance() { if (s == null) s = new Singleton(); return s; } } // 测试类 class singletonTest { public static void main(String[] args) { Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); if (s1==s2) System.out.println ("s1 is the same instance with s2"); else System.out.println ("s1 is not the same instance with s2"); } }
class SingletonException extends RuntimeException { public SingletonException(String s) { super(s); } }
class Singleton { static boolean instance_flag = false; // true if 1 instance public Singleton() { if (instance_flag) throw new SingletonException ("Only one instance allowed"); else instance_flag = true; // set flag for 1 instance } }
// 测试类
public class singletonTest { static public void main(String argv[]) { Singleton s1, s2; // create one incetance--this should always work System。out.println ("Creating one instance"); try { s1 = new Singleton(); } catch (SingletonException e) { System.out.println(e.getMessage()); } // try to create another spooler --should fail System.out.println ("Creating two instance"); try { s2 = new Singleton(); } catch (SingletonException e) { System.out.println(e.getMessage()); } } }
singletonTest运行结果是:
Creating one instance Creating two instance Only one instance allowed