2017-04-26 43 views
0

我有一個配置服務器的類。服務器對象是靜態的並且被初始化。問題是,服務器的一些配置來自包含類的非靜態成員變量。顯然,非靜態成員不能被訪問。有沒有辦法解決這個問題,我可以配置我的服務器使用非靜態變量?服務器必須保持靜態。Static Lazy Initializer

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

會發生什麼?你的問題很奇怪而且抽象。你想用哪些非靜態變量來配置你的服務器?他們應該從哪裏來?當然,您可以將非靜態變量作爲參數傳遞給'getMyServer'方法。但是,如果你不想這樣 - 他們應該從哪裏來? –

+0

當您調用getMyServer函數時,唯一的方法是使用ClassA的實例作爲參數。順便說一句,「靜態懶惰吸氣」是calles單身模式。 – Armin

回答

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; 
    } 
}