Java:按枚举类型不同的返回类型

时间:2019-08-25 13:53:31

标签: java generics types return

我想知道是否可以有多个返回类型,这些返回类型由方法的enum参数给出。

例如:

public <T extends ICloudServer> T startServer(ServerType type) {
  ...
}

如果服务器类型是PROXY,我想返回一个ProxyServer,如果服务器类型是MINECRAFT,我想返回一个MinecraftServer。

有什么方法可以用Java实现呢?

1 个答案:

答案 0 :(得分:2)

使服务器实现ICloudServer接口,并将start方法添加到ServerType枚举中,作为服务器启动 strategy 方法。不同的服务器具有不同的配置和启动过程。

class Minecraft implements ICloudServer{

    //ctor
    Minecraft(ServerConfig cfg){
         //ctor implementations
    } 

    //Other implementation details
}

public enum ServerType {

    MINECRAFT { 
        @Override
        public ICloudServer start(ServerConfig cfg ) {      
            //Apply config for minecraft
            Minecraft server = new Minecraft(cfg.port()).username(cfg.username()).password(cfg.password()).done();
             //Start minecraft server 
            server.start();
            return  server;
        }
    },

    PROXY {
        @Override
        public ICloudServer start(ServerConfig cfg) { 
            //Apply config and start proxy server
            ProxyServer server = new ProxyServer(cfg);           
            return server;
        }
    };
    public abstract ICloudServer start(ServerConfig port) throws Exception;
}

@JB Nizet提到将startServer方法的返回类型更改为ICloudServer,只需调用ServerType#start(ServerConfig cfg)即可启动服务器。

public ICloudServer startServer(ServerType type) {  

    try{
       return type.start(new ServerConfig());
    }catch(Exception ex){
        //log exception
    }

    throw new ServerStartException("failed to start server");
}