[英]How does one share a single name among a group of Java Objects?
The title may or may not make sense, but my question is how can I "override" an object to a different type? 标题可能有意义,也可能没有意义,但我的问题是如何将一个对象“覆盖”为另一种类型?
I doubt this is even possible, but I'm not quite sure how to tackle this problem any other way. 我怀疑这是可能的,但我不太确定如何以任何其他方式解决这个问题。
I am creating a small platforming game in Java, and all the levels are assigned to class objects. 我正在用Java创建一个小型平台游戏,所有级别都分配给类对象。 Such as Level 1 would be in the class Level1, and instantiated by:
如Level 1将在Level1类中,并通过以下方式实例化:
Level1 platforms = new Level1();
The way I draw objects (and similarly check for collision) is described in this loop: 我在这个循环中描述了绘制对象的方式(以及类似地检查碰撞):
Level1 platforms = new Level1();
//grabs number of platforms for level 1
int platformNum = platforms.getNumberOfPlatforms();
//creates platforms for level 1
for(int i=0;i<=platformNum;i++){
int x1=platforms.getPlatformCoords(i,1);
int y1=platforms.getPlatformCoords(i,2);
int x2=platforms.getPlatformCoords(i,3);
int y2=platforms.getPlatformCoords(i,4);
x2-=x1;
y2-=y1;
g.fillRect(x1,y1,x2,y2);
}
How can I change the statement Level1 platforms = new Level1();
如何更改语句
Level1 platforms = new Level1();
so that platforms
can be of a certain type depending on a variable level
, such that when level == 1
, platforms will be of Level1
, and so forth? 所以
platforms
可以是某种类型,具体取决于变量level
,这样当level == 1
,平台将是Level1
,依此类推?
Just use a FactoryMethod: 只需使用FactoryMethod:
Level platform = LevelFactory.getLevel(level);
Inside LevelFactory: Inside LevelFactory:
public Level getLevel(int level){
if(level==1)return new Level1();
if(level==2)return new Level2();
//...
}
In order for this to work, each level has to extend or implement a Level class or interface. 为了使其工作,每个级别必须扩展或实现Level类或接口。
There's a bit of a code smell to this, but what I think you want is an interface for a basic Level
. 这有一点代码味道,但我认为你想要的是一个基本
Level
的界面。 To add to that, you're going to want to use a factory to create the levels for you on the fly. 除此之外,您还希望使用工厂为您即时创建关卡。
public class LevelFactory {
public Level getLevel(int level) {
switch(level) {
case 1:
return new Level1();
case 2:
return new Level2();
default:
throw new IllegalArgumentException("Level not valid");
}
}
}
public interface Level {
int getNumberOfPlatforms();
int getPlatformCoords(int x, int y);
}
In that instance, so long as all of your levels implement Level
... 在那种情况下,只要你的所有级别都实现
Level
...
public class Level1 implements Level { }
public class Level2 implements Level { }
...you would just need to get the level you care about at the time to use. ...你只需要在使用时获得你关心的水平。
Level platforms = LevelFactory.getLevel(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.