我有一个配置服务器的类。服务器对象是静态的,并且是惰性初始化的。问题是,服务器的一些配置来自包含类的非静态成员变量。显然,无法访问非静态成员。有没有解决方法,我可以使用非静态变量配置我的服务器?服务器必须保持静态。
public class ClassA {
private static MyServer myServer;
private int a;
private int b;
public ClassA(int a, int b) {
this.a = a;
this.b = b;
}
public static MyServer getMyServer() {
if(myServer == null) {
myServer = configureServer();
}
return myServer;
}
private static MyServer configureServer() {
MyServer myServer = new MyServer();
myServer.setaPlusB(a + b);
return myServer;
}
}
public class MyServer {
private int aPlusB;
public void setaPlusB(int aPlusB) {
this.aPlusB = aPlusB;
}
}
答案 0 :(得分:1)
从你的问题来看,我理解如下:
public class Server {
private class ServerImpl {
private int ab;
public ServerImpl() {
ab = Server.a + Server.b;
}
}
private static int a;
private static int b;
private static ServerImpl s;
static {
a = 10;
b = 10;
}
public static ServerImpl getServer(int newA, int newB) {
a = newA;
b = newB;
return getServer();
}
public static ServerImpl getServer() {
if (s == null) {
s = new ServerImpl();
}
return s;
}
}