如何调用接口的特定实现类

时间:2013-12-25 22:41:39

标签: java class interface enums

我尝试完成的是调用特定类的接口 我使用Enum来填充.class并获取该类的接口 那么我怎样才能返回界面呢? 如果可能的话,我想避免反思。

提前致谢。

public interface GameInterface {
    void start();
    void sop();
}

public enum Game{
    MINESWEEPER(MineSweeper.class),
    MARIO(Mario.class);

    private Class c;

    public Game(Class c) {
        this.c = c;
    }

    public GameInterface getGameInterface() {
        // return Interface of the class 
        // So I can call for instance MINESWEEPER.getGameInterface().start()

        // At this momement I use return: 
        // ((GamemodeInterface)this.c.getDeclaredMethod("getInstance", new Class[0]).invoke(null, new Object[0]));
        // *MineSweeper and Mario are Singleton, thats why getInstance
    }
}

澄清: 主要目标是在MineSweeper和Mario类中访问Start()和Stop()方法 用法应该是这样的:MINESWEEPER.getGameInterface()。start() 但是目前我还不知道一个可靠的解决方案,让界面知道.class。

1 个答案:

答案 0 :(得分:5)

更好的主意:

  1. 在您班级的每个游戏中实施GameInterface,并隐含您选择的名称。
  2. 使用抽象函数enum声明createGame,并将每个createGame函数实现此enum函数所期望的Game类实例返回给每个class MineSweeper implements GameInterface { // your code } class Mario implements GameInterface { // your code } public enum GameType { MINESWEEPER { public GameInterface createGame() { return new MineSweeper(); } }, MARIO { public GameInterface createGame() { return new Mario(); } } public abstract GameInterface createGame(); } 常量:

    MineSweeper.getInstance()
  3. 如果你打算使用单身模式,虽然我不能确定你的问题,但正如@GaborSch建议的那样:你可以在createGame() enum内使用enum函数常量。但是,尝试在实现Singleton的同时使用{{1}},正如Effective Java书中详细说明所示。