singleton 单例
今天为了实现一个窗体只能打开一次,用到了单例模式,详细如下
Singleton模式主要作用是确保在Java应用程式中,一个类Class只有一个实例存在。
1:
public class Singleton2 {
private Singleton2(){}
private static Singleton2 instance = null;
// synchronized确保同步
public static synchronized Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}
return instance;
}
}
2:
public class Singleton {
private Singleton(){}
static class SingletonHolder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}