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

多米尼克语:

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

例如:

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

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

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

蓝云:

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

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提到的,将change 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");
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章