有一种方法。在一种情况下,我需要返回一种类型的变量。在另一种情况下,我需要返回另一种类型的变量。我创建了两种方法。但我知道,由于代码的公开,这不是一个好主意。知道如何解决它并使用一种方法吗?
public ClassA doSomething(String aString, String bString, String cString, String dString) {
ClassA client;
ClientFactory clientFactory = new ClientFactoryImpl();
client = clientFactory.createNewClient(aString, bString);
ClassB conn = clientFactory.connect(cString, dString);
return client;
}
public ClassB doSomething(String aString, String bString, String cString, String dString) {
ClassA client;
ClientFactory clientFactory = new ClientFactoryImpl();
client = clientFactory.createNewClient(aString, bString);
ClassB conn = clientFactory.connect(cString, dString);
return conn;
}
答案 0 :(得分:1)
一般情况下,当客户和conn相互依赖时:
class SomethingResult {
ClassA client;
ClassB conn;
SomethingResult(ClassA client, ClassB conn) {
this.client = client;
this.conn = conn;
}
// Getters
}
public SomethingResult doSomething(String aString, String bString, String cString, String dString) {
// Create client and conn and execute any other logic
return new SomethingResult(client, conn);
}
然后,例如,获取客户端:
ClassA client = doSomething(aString, bString, cString, dString).getClient();
在您的具体情况下,没有必要这样做;你可以这样做:
public ClassA getClient(String aString, String bString) {
ClientFactory clientFactory = new ClientFactoryImpl();
return clientFactory.createNewClient(aString, bString);
}
public ClassB getConn(String cString, String dString) {
ClientFactory clientFactory = new ClientFactoryImpl();
return clientFactory.connect(cString, dString);
}