java - 关于单例设计模式

标签 java design-patterns singleton

我在探索单例设计模式,我开发了一个类...

public class SingletonObject {
  private static SingletonObject ref;       
  private SingletonObject () { //private constructor
  }     
  public static synchronized SingletonObject getSingletonObject() {
    if (ref == null)
      ref = new SingletonObject();
    return ref;
  } 

  public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException ();
  }
}

但是同步的成本非常高,所以我转而采用新设计的热切创建实例,而不是懒惰创建的实例。

public class Singleton {
  private static Singleton uniqueInstance = new Singleton();
  private Singleton() {
  }
  public static Singleton getInstance() {
    return uniqueInstance;
  }
}

但是请告诉我第二种设计比以前的设计有什么优势..!!

最佳答案

Josh Bloch 建议使用枚举:

   public enum Foo {
       INSTANCE;
   }

有关解释,请参阅他的 Effective Java Reloaded在 Google I/O 2008 上发表演讲。

总结:

"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

关于java - 关于单例设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10250799/

相关文章:

java - 如何获取 Hashmap Key 并将其转换为其他数据类型

design-patterns - Microsoft 的并行模式库 : anyone looked to see how hard it'd be to port to POSIX/Linux?

language-agnostic - 你会在哪里使用构建器模式而不是抽象工厂?

c++ - 为什么这个 C++ 静态单例永远不会停止?

c# - Excel 应用程序单例 - 仅使用一个 Excel 应用程序实例而不退出的可能威胁?

java - 运行 Activity 两次(而不是一次)以从 getter 获取值

java - 如何在java中计算格式化字符串如 '1,000,000*2'

makefile - 如何获取模式规则来匹配 Makefile 中的文件名和空格?

c++ - 创建具有构造函数的单例类,该构造函数接受运行时评估的参数

java - SpringJunit4ClassRunner 的类路径在哪里,如何直接指向我操作系统中的文件?