再舉個例子,集合中的 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