Reputation: 6148
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
Upvotes: 0
Views: 115
Reputation: 6148
I can load from jar by creating classloder like this
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");
But it may happen that it will not Garbage collected and May leak will happen
Upvotes: 0
Reputation: 681
You can use factory pattern to achieve your objective.
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();
}
you may search more abour Factory Pattern.
Upvotes: 0
Reputation: 17
Use abstract factory Pattern or Factory Pattern.
public Game createGame(GameType gameType){
Game game = null;
Switch(gameType){
Case FOOTBALL :
game = new FootBall();
Case CRICKET :
game = new Cricket()
}
return game;
}
Where CreateGame method is Factory class method.GameType is Enum
Upvotes: 1
Reputation: 77206
You should not do this. Instead, define an interface Play
that has a playGame()
method, and create different classes that implement the interface.
Upvotes: 1
Reputation: 15518
This looks like it could be solved with an "abstract/template method pattern". Instead of your 5 jars, you will have an abstract base class defining the common behaviour, and 5 concrete implementations of the abstract class. When you click on the button reading football, you will execute the football implementation and so on
Upvotes: 1