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;
}

}





posted @ 2009-01-06 14:42  因是因非  阅读(230)  评论(0编辑  收藏  举报