Singleton模式: Singleton模式主要作用是保證在java應用程序中,一個Class只有一個實例存在。 一般有三種方法: 1 定義一個類,它的構造函數為PRivate的,所有方法為static的。如java.lang.Math 其他類對它的引用全部是通過類名直接引用。例如: public final class Math {
/** * Don't let anyone instantiate this class. */ private Math() {}
public static int round(float a) { return (int)floor(a + 0.5f); } ... }
2 定義一個類,它的構造函數為private的,它有一個static的private的該類變量,在類初始化時 實例話,通過一個public的getInstance方法獲取對它的引用,繼而調用其中的方法。例如: public class Runtime {
private static Runtime currentRuntime = new Runtime();
class PrintSpooler { //this is a prototype for a printer-spooler class //sUCh that only one instance can ever exist static boolean instance_flag=false; //true if 1 instance public PrintSpooler() throws SingletonException { if (instance_flag) throw new SingletonException("Only one spooler allowed"); else instance_flag = true; //set flag for 1 instance System.out.println("spooler opened"); } //------------------------------------------- public void finalize() { instance_flag = false; //clear if destroyed } }