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");
}
}
singletonTest運行結果是:
s1 is 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
可以看出,第一個執行個體順利建立,第二個執行個體建立實拋出了我們自訂的異常.