0

I have Five Jar files.All jar files contain Same Class Play And Same Method PlayGame() But having different logic of playing game. Example :

Class Play{

     public String PlayGame(){
             //logic for playing Game
             //each jar contain different logic for playing game
     }
} 

I have One main application and it contains all five jars included. My main application calls PlayGame() method.

I want that, on football select, PlayGame() method of football jar should be called. On hockey select, PlayGame() method of Hockey jar should be called. So on...

My all different implementation of playing game are in different jars. Because My application accepts jar from user of his implementation and places it in classpath and Restarts application.

Please help,How i should proceed to achieve this. Thank You

4

5 回答 5

1

使用抽象工厂模式或工厂模式。

 public Game createGame(GameType gameType){
   Game game = null;
   Switch(gameType){
       Case FOOTBALL :
       game = new FootBall();
       Case CRICKET :
       game = new Cricket()
  }
 return game;
 }

其中 CreateGame 方法是工厂类方法。GameType 是 Enum

于 2013-09-17T10:27:25.330 回答
1

这看起来可以用“抽象/模板方法模式”来解决。您将拥有一个定义常见行为的抽象基类和抽象类的 5 个具体实现,而不是 5 个 jar。当你点击阅读足球的按钮时,你会执行足球的实现等等

于 2013-09-17T10:13:15.057 回答
1

你不应该这样做。相反,定义一个interface Play具有playGame()方法的类,并创建实现该接口的不同类。

于 2013-09-17T10:15:07.800 回答
0

我可以通过像这样创建类加载器来从 jar 加载

    File file  = new File("c:\\myjar.jar");
    URL url = file.toURL();  
    URL[] urls = new URL[]{url};
    ClassLoader loader = new URLClassLoader(urls);
    Class cls = loader.loadClass("com.mypackage.Play");

但是可能会发生它不会收集垃圾并且可能会发生泄漏

于 2013-10-21T12:45:38.133 回答
0

您可以使用工厂模式来实现您的目标。

public void playGame(GameType gameType){
  Game game = null;
  if(gameType instanceof Football){
      game = new Football();
  }else if(gameType instanceof BasketBall){
      game = new BasketBall();
  }
  game.play();
}

您可以搜索更多关于工厂模式的信息。

于 2013-10-01T07:37:27.733 回答