我想做的只是创建一个类,当你扩展它时,你会自动获得 getInstance 类。问题是,当我扩展它时,我无法引用子类。我能看到的唯一方法是通过类型转换 ((ClassName)class.getInstance()) 但它不是很用户友好。有什么建议么?
问问题
24866 次
2 回答
11
您不能扩展正确的 Singleton,因为它应该有一个私有构造函数:
有效的 Java 项目 2:使用私有构造函数强制执行单例属性
于 2013-04-29T03:12:39.537 回答
3
覆盖单例的唯一方法是拥有一个期望被覆盖的单例。最简单的方法是提供单例,它实现了一个interface
(或者完全是abstract
它自己),它在第一次使用getInstance()
.
public interface SingletonMethods // use a better name
{
String getName();
void doSomething(Object something);
}
public class Singleton // use a better name
{
private Singleton() { /* hidden constructor */ }
public static SingletonMethods getInstance()
{
return SingletonContainer.INSTANCE;
}
/**
* Thread safe container for instantiating a singleton without locking.
*/
private static class SingletonContainer
{
public static final SingletonMethods INSTANCE;
static
{
SingletonMethods singleton = null;
// SPI load the type
Iterator<SingletonMethods> loader =
ServiceLoader.load(SingletonMethods.class).iterator();
// alternatively, you could add priority to the interface, or
// load a builder than instantiates the singleton based on
// priority (if it's a heavy object)
// then, you could loop through a bunch of SPI provided types
// and find the "highest" priority one
if (loader.hasNext())
{
singleton = loader.next();
}
else
{
// the standard singleton to use if not overridden
singleton = new DefaultSingletonMethods();
}
// remember singleton
INSTANCE = singleton;
}
}
}
于 2013-04-29T03:36:19.837 回答