处理必须进行子类化的单例 [英] Dealing with Singletons which have to subclass
问题描述
在问题在Java中实现单例模式的有效方法是什么?最大的升值的答案是使用枚举来实现单例。
这很好,我理解论据,分别是语言的优点。
然而,我有一组我定义单例但需要扩展其他类的类,这是不可能的枚举方法,因为枚举不能子类。
Joshua Bloch在幻灯片中说:
- 但有一件事丢失 - 您不能扩展枚举类型
- 在大多数情况下,您不应该
- 一个引人注目的用例操作代码
在大多数情况下,您不应该:可以有人详细说明了?我已经实现了几个servlet,它们扩展了 HttpServlet
,为什么这些servlet不是单例?我只需要我的应用程序中的一个实例。
Singleton类可以扩展其他类;实际上默认情况下在Java中将会扩展Object。但是Josh所指的是你不应该扩展一个Singleton类,因为一旦你扩展它,就有超过1个实例存在。
回答评论: / p>
实际上,实现Singleton的最佳方式是:
从有效的Java
//具有静态工厂的Singleton
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis(){...}
public static Elvis getInstance(){return INSTANCE; }
public void leaveTheBuilding(){...}
}
这里Elvis可以扩展任何其他类。
In the question What is an efficient way to implement a singleton pattern in Java? the answer with the most upvotes says, to use a Enum for implementing a singleton.
That is fine and I understand the arguments, respectively the language advantages.
I have, however, a set of classes which I define singleton but which need to extend other classes, this is not possible with the enum approach, since enums cannot subclass.
Joshua Bloch says in his slides:
- But one thing is missing—you can’t extend an enum type
- In most cases, you shouldn’t
- One compelling use case—operation codes
In most cases you shouldn't: could someone elaborate on that? I have implemented several servlets and they extend HttpServlet
, why shouldn't these be singletons? I only want one instance of them in my application.
A Singleton class can extend other classes; actually by default in Java it would anyway extend Object. However what Josh is referring to is that you shouldn't extend a Singleton class because once you extend it, there is more than 1 instance present.
Answering the comment:
Actually the best way to implement the Singleton is:
From Effective Java
// Singleton with static factory
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis() { ... }
public static Elvis getInstance() { return INSTANCE; }
public void leaveTheBuilding() { ... }
}
Here Elvis can extend any other class.
这篇关于处理必须进行子类化的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!