[英]Java Implementable Class Creation?
因此,我想制作一个游戏引擎,我立即意识到必须将这些东西“自动导入”。 例如,当您implements Runnable
,您会得到一个错误,因为它必须在类中具有run()
方法。
你怎么做到这一点? 在实现时,我将如何拥有一个类,强制一个方法,然后自动运行该方法?
一个示例,在回答时可用:
我有一个框架课。 该框架类在实现时将始终在实现该类的类中使用一个名为draw()
,并且将被实现为使用该框架类。 示例代码:
public class test implements HFrame {
// constructor
public test() {
}
// method called when test is run
public static void init() {
HFrame f = new HFrame(WIDTH, HEIGHT);
f.display(); // makes the frame visible
}
// method that frame will always call when it is implemented
public void draw() {
// stuff to draw
new Circle(0, 0, 50, 50);
}
}
使用评论,我将如何使其工作?
感谢您的帮助,如果这不是最好的话,我深表歉意。
用您要运行的方法创建一个接口。 将要使用的所有类都必须实现该接口。 这就是Runnable
工作方式: Runnable
是一个接口,其中有一个方法void run()
,Thread可以调用该方法void run()
Runnable
。
为了“强制”类实现某些方法,请使用接口,下面是一个示例
public interface GameEngineInterface {
void init();
void draw();
Vector3d annotherMethod(Object object);
}
Game引擎将使用的任何类都将实现GameEngineInterface引擎。
GameEngine方法可以这样工作
public Object someMethod(GameEngineInterface anyObjectThatImplementsGameEngineInterface){
//method body
}
然后,GameEngine不在乎隐含方法的细节,只是它可以调用那些方法。
看起来您需要实现Template Method设计模式 。 在您的示例中, run
将调用draw()
,该方法必须在具体的类中实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.