参数化类的java单例
我无法解开这个纠缠。
public class MySingleton<T extends AUsefulClass>{
Map<String, T> myUsefulRegistry;
private static MySingleton<T> _instance = null;
public static instance(){
if(instance == null)
_instance = new MySingleton<T>();
return _instance;
}
}
public class Test{
@Test
public void testThis(){
MySingleton<SomeClass> mySingleton = MySingleton<SomeClass>().instance();
}
}
这种参数化是错误的,因为您无法对非静态 T 进行静态引用。不过,我想构建一个可参数化的单例类。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是,在 Java 中(与 .NET 不同),无论您提供多少种不同类型的参数,您都只有一个静态变量 - 因此
MySingleton._instance
等于MySingleton< ;栏>._实例
。我怀疑你想要一个
Map, MySingleton>
,抑制有关原始类型的警告。然后,您可以让您的instance
方法也采用Class
参数,以便它知道要查找什么。当然,这是假设您想要不同类型参数的单独状态。如果您不需要
MySingleton
和MySingleton
需要不同的状态,您可以真正拥有一个实例,然后只需进行强制转换它同时抑制未经检查的转换警告。The problem is that in Java (unlike .NET) you've only got one static variable no matter how many different type arguments you provide - so
MySingleton<Foo>._instance
is equal toMySingleton<Bar>._instance
.I suspect you want a
Map<Class<? extends AUsefulClass>, MySingleton>
, suppressing the warnings about raw types. Then you'd make yourinstance
method take aClass<T>
parameter as well, so it would know what to look up.Of course, this is assuming you want separate state for different type arguments. If you don't need different state for
MySingleton<Foo>
andMySingleton<Bar>
you can truly have a single instance, and just cast it while suppressing the unchecked conversion warning.解决方案如下:
如果您计划重新分配
myUsefulRegistry
,则显然必须省略 final 修饰符,并根据type
实现状态参数(通过存储它以供再次使用)。编辑:如果用户传递与原始类型不同的类型,则会出现问题。在任何情况下您可能都希望存储该类型,因此您可以检查对
getInstance(Class)
的任何后续调用是否有效。Here's a solution:
If you are planning on reassigning
myUsefulRegistry
, you will obviously have to omit the final modifier and also implement state based on thetype
parameter (by storing it to use again).Edit: There's an issue if the user passes a different type to the original. You may want to store the type in any case then, so you can check whether any proceeding calls to
getInstance(Class<T>)
are valid.在这种情况下,我宁愿看看我的设计。另外,如果你想根据情况创建不同的单例。您可能首先会使用工厂来实例化单例。
我不确定单例模式是否是一个好方法,它通过对象引入全局状态,这正是您可能不想要的。
I'd rather look at my design in this case. Also, if you want to create a different singleton due circumstances. You'd probably use a factory to instantiate the singleton at first.
I'm not sure if the singleton pattern is a good approach, it introduces global state via objects, which is the very thing you probably don't want.