【发布时间】:2012-02-17 19:59:30
【问题描述】:
这是一个简单的例子:
class World<S extends Sprites, B extends Bodies> {
// Both of these have a problem...
static World world = null; // "World is a raw type. References to generic type
// World<BOD,SPRT> should be parameterized"
static World<S, B> world = null; // "Cannot make a static reference to the non-static type S
// "Cannot make a static reference to the non-static type B
// The following is allowed but looks ugly/fishy to me
static World<?, ?> world = null; //
如果您想知道,我正在尝试实现单例模式。挑战在于这个类在一个单独的包 GAME 中扩展,我不能让这个包(模型)对那个 GAME 有任何依赖。因此构造函数必须是模型。所以可以让Constructor将单例对象存储在MODEL中这个类的静态变量中。
您认为static World<?, ?> world = null; 确实丑陋吗?有没有更好的方法来解决这个问题?
【问题讨论】:
-
记住Java有类型擦除;将只有一个静态
world变量,无论您实例化World类有多少不同的方式(因为就运行时而言它们都共享同一个类)。 -
一开始我不会让 World 成为单例/静态的。当你编写一个存在两个世界的不同游戏时会发生什么?无论如何,在我看来,要确保 it 只创建一个
World,这取决于您的GAME包中的任何内容。这以现在的方式回答了您的问题,而是避免了这个问题。 -
好点...实际上我的 GAME 包实现了一个传统的单例以确保只有一个...
标签: java generics inheritance singleton