简体   繁体   中英

How can I return a class choosing between 2 classes?

I wanted to know if is it possible to have a method that can choose between multiple classes and return one of them.

This is what it should look like:

public class BotManager {
public static Test test;
public static int PROTOCOL_VERSION = 114;

public Bot bot(){
    if(PROTOCOL_VERSION == 114){
        return test.bot114;
    }else{
        return test.bot111;
    }
}

in this example, bot111 and bot114 are different classes.

bot.version111.bot.Bot;

bot.version114.bot.Bot;

Yeah of course you can.
You just need to be sure that bot114 and bot111 both extend the Bot class.

For these purposes you would use what's called a factory, here is an example of a factory that returns different Windows based on the Class type:

  public static Window getCsvExportWindow(Class tab) {
        if (tab == OnhandTab.class) {
            return new OnhandCsvExportWindow();
        } else {
            return new CustOrderCsvExportWindow();
        }
   }

Instead of Class type you use your PROTOCOL_VERSION.

You can use it's code:

if (Object object instanceof Bot114) {
  return new Bot114();
} else if (Object object instanceof Bot111) {
  return new Bot111();
} else {
  return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM