【发布时间】:2011-04-19 01:10:48
【问题描述】:
在 C# 中,我们可以定义一个通用的class A<T> where T : new()。在这段代码中,我们可以用new T() 创建一个T 的实例。这是如何在 Java 中实现的?我读了一些文章说这是不可能的。
我使用 C# 中使用泛型的单例模式的原因如下:
public static class Singleton<T> where T : new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = SingletonCreater.Instance;
}
return instance;
}
}
static class SingletonCreater
{
internal static readonly T Instance = new T();
}
}
以及如何让这个方法更优雅?
【问题讨论】:
-
顺便说一下,你可能对这个帖子感兴趣:stackoverflow.com/questions/75175/…
标签: c# java generics design-patterns