問題描述
Java:枚舉的不同返回類型 (Java: Different return type by enum)
我想知道是否可以有多個返回類型,這些返回類型由方法中的枚舉參數給出。
例如:
public <T extends ICloudServer> T startServer(ServerType type) {
...
}
如果服務器類型是 PROXY ,我想返回一個 ProxyServer,如果服務器類型是 MINECRAFT,我想返回一個 MinecraftServer。
有沒有辦法用 Java 來實現?
參考解法
方法 1:
Make servers implement ICloudServer
interface and add start
method into ServerType
enum to be server starting‑up strategy method. Different server has different configuration and start up procedures.
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;
}
As @JB Nizet mentioned change startServer
method return type to ICloudServer
and simply call ServerType#start(ServerConfig cfg)
to start the server.
public ICloudServer startServer(ServerType type) {
try{
return type.start(new ServerConfig());
}catch(Exception ex){
//log exception
}
throw new ServerStartException("failed to start server");
}