2012-07-17 66 views
0

首先,我很抱歉如果這是一個愚蠢的問題。這是最近困擾着我,我想這是值得一問...你如何將主要創建的實例傳遞給類?

我所在班流,像這樣的應用程序:

enter image description here

我正在試圖讓我的客戶端類和「服務器」類訪問在MyApp中創建的對象的實例。問題是實例是在main中創建的(因此使它們成爲靜態的),我想知道如何正確地將它們傳遞給其他類,因爲我所做的似乎並不是正確的方式。

這裏是我做了什麼:

public class MyApp { 
    private static RedClient red_client = null; 
    private static BlueClient blue_client = null; 
    private static RedServer red_server = null; 
    private static BlueServer blue_server = null; 

    public static void main(String[] args) { 
     final Client myClient = new Client(arg1, arg2); 
     red_client = myClient.getRedClient(); 
     blue_client = myClient.getBlueClient(); 

     final Server myServer = new Server(arg3, arg4); 
     red_server = myServer.getRedServer(); 
     blue_server = myServer.getBlueServer(); 
    } 

    public static RedClient getRedClient() { 
     return red_Client; 
    } 

    public static BlueClient getBlueClient() { 
     return blue_client; 
    } 

    public static RedServer getRedServer() { 
     return red_server; 
    } 

    public static BlueServer getBlueServer() { 
     return blue_server; 
    } 

} 

我以後會利用以下,像這樣的:

public class Client { 
    public void SomeMethod { 
     MyApp.getBlueServer.doSomething(myObject); 
    } 
} 

我只是不能確定這是否是合格的有道作爲客戶端和服務器的其他類的實例都與MyApp進行通信。 (請忽略類名,因爲它們與應用程序的功能無關,我只是將它們用作名稱,因爲這是我能想到的第一件事)。

如果你需要澄清,讓我知道,因爲我願意接受學習和批評。如果這是錯誤的方式,你能解釋爲什麼它是錯誤的,然後解釋正確的方法。

編輯

進一步澄清:

  • MyApp的訪問客戶端&服務器
  • 客戶端訪問RedClient & BlueClient
  • 服務器訪問RedServer & BlueServer

沒有其他類可以互相訪問。

回答

2

我沒有看到你傳遞/設置任何東西。

沒有理由不能傳遞到服務器的客戶端的情況下(反之亦然):

Client myClient = new Client(args); 
Server myServer = new Server(args); 

BlueClient = myClient.getBlueClient(); 
RedCLient = myClient.getRedClient(); 

BlueServer = myServer.getBlueServer(); 
RedServer = myServer.getRedServer(); 

myClient.addServer(blueServer); 
myClient.addServer(redServer); 

myServer.addClient(blueClient); 
myServer.addClient(redClient); 
+0

我很抱歉沒有澄清這一點。我對原始問題進行了編輯,說明哪些類可以訪問哪些類。因此,MyApp創建客戶端和服務器,但不能直接訪問RedClient,BlueClient等。你是否建議我添加一些setter並直接從main設置? – WilliamShatner 2012-07-17 18:58:53

+0

沒有理由不能這樣做。 – jahroy 2012-07-17 19:10:32

+0

您甚至可以在'Client'中編寫一個方法,該方法接收對「Server」的引用並添加其所有不同顏色的服務器......您有很多選項。 – jahroy 2012-07-17 19:12:17

1

我不知道你問什麼,但我認爲你需要閱讀一些關於首先面向對象編程。

您剛纔介紹的情況下(我不喜歡它,但它的更好,我覺得)你可能有客戶端構造函數收到服務器作爲一個參數:

Client client1 = new CLient(server1) 

這樣你就可以從客戶端方法訪問server1對象。

+0

如果可能,我不想添加構造函數。謝謝你的回答,雖然 – WilliamShatner 2012-07-17 18:55:51

1

你可以使用單身。如果你有一個類,並且你可以確定總是有最大的一個實例,那麼這個實例就是一個單例。我給你一個小例子:

public class MyClass { 
    private static MyClass instance; 
    public static MyClass getInstance() { 
     if(instance == null) 
      instance = new MyClass(); 
     return instance; 
    } 
    private MyClass() { } 
} 

這一點,從你的代碼的任何地方,你可以調用MyClass.getInstance(),你會得到一個單;考慮一下;對於你所談論的情況,這可能是非常實際的。

+0

謝謝你的例子,我將不得不閱讀單身。但是,是的,據我所知,在任何時候都只有一個班級。 – WilliamShatner 2012-07-17 18:59:55

相關問題