我已经阅读了单例设计模式的概念,并理解为了制作类单例,我们必须执行以下步骤:
1)私有构造函数,用于限制其他类实例化该类。
2)同一个类的私有静态变量,是该类的唯一实例。
3)返回类实例的公共静态方法,这是外部世界获取单例类实例的全局访问点。
所以我的班级看起来像这样:
public class Singleton {
private static Singleton singleton =new Singleton();;
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){
System.out.println("Creating new now");
}
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
public void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
但是这里我们如何确保只创建一个 Singleton 实例呢?假设我有 2 个类 Singletondemo1 和 Singletondemo2。 在 Singletondemo1 中,我调用 getInstance() 并创建一个对象。同样的方式我也可以在 Singletondemo2 中做到这一点。
那么我们如何确保只创建对象并且它是线程安全的。
在您的示例中,没有检查确保全局或所需范围内仅存在一个实例。
public class Singleton {
private static Singleton instance;
public String value;
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(String value) {
// The following code emulates slow initialization.
// It also could initialize something during the singleton creation.
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
this.value = value;
}
/**
* Checks if there is already a Singleton instance.
* If not, creates a new instance and returns it.
*/
public static Singleton getInstance(String value) {
if (instance == null) {
instance = new Singleton(value);
}
return instance;
}
/* Other methods protected by singleton-ness */
public void demoMethod( ) {
//
}
}