2014-01-24 57 views
-2

數據庫(字符表)只能通過實現接口類型IConnection的類訪問。 數據庫應該是Singleton,但只有一個具體的連接應該使用它(不是主要功能)。 連接應該是Multitons:在round-robin fasion(1 2 3 1 2 3 ...)中只有三個由getInstance方法返回。 客戶端(主函數)獲取連接對象並使用它訪問數據庫。 請完成以下代碼。在主要功能:獲得4個連接,並證明他們都使用相同的數據庫。然後證明實際上(儘管有4個初始化引用),只存在3個連接對象。我怎麼能在數據庫中使用multiton?

我無法提供持續...下面的示例代碼...

interface IConnection { 
    char get(int index); 
    void set(int index, char c); 
    int length(); 
} 

class Database { 

    private char[] tab = new char[100]; /* ... */ 

    public static IConnection getConnection() { 
     return Connection.getInstance(); 
    } 

    private static class Connection implements IConnection { 

     private Database db; 
     private static IConnection instance = getConnection(); 

     public static IConnection getInstance() { 

     public char get(int index) { 
      return db.tab[index]; 
     } 

     public void set(int index, char c) { 
      db.tab[index] = c; 
     } 

     public int length() { 
      return db.tab.length; 
     } 
    } 
} 
+0

請縮進您的界面。我看不懂這個。我注意到你沒有向getInstance()傳遞一個鍵(Multiton是一個Singleton,其中'getInstance()'有一個鍵)。 –

+0

我編輯代碼...實際上,這是我的第一個單身人士和multiton類......我無法做到:S – hydrojan

+0

我不能確切地告訴你在這裏問什麼?你問你應該如何實現getInstance? – jsight

回答

0

這裏是一個可能的答案

public static interface IConnection { 
    char get(int index); 

    void set(int index, char c); 

    int length(); 
} 

public static class Database { 
    private char[] tab = new char[100]; 

    public static IConnection getConnection() { 
     return Connection.getInstance(); 
    } 

    private static final class Connection implements IConnection { 
     private Database db; 
     private Connection() { 
      super(); 
     } 
     private static IConnection[] instance = new IConnection[3]; 
     static { 
      for (int i = 0; i < instance.length; i++) { 
       instance[i] = new Connection(); 
      } 
     } 
     private static int i = 0; 
     public static IConnection getInstance() { 
      return instance[(i++)%instance.length]; 
     } 

     public char get(int index) { 
      return db.tab[index]; 
     } 

     public void set(int index, char c) { 
      db.tab[index] = c; 
     } 

     public int length() { 
      return db.tab.length; 
     } 
    } 
} 
public static void main(String[] args) { 
    IConnection conn1 = Database.getConnection(); 
    IConnection conn2 = Database.getConnection(); 
    IConnection conn3 = Database.getConnection(); 
    IConnection conn4 = Database.getConnection(); 
    if (conn1 == conn4) { 
     System.out.println("conn1 has the same reference as conn4"); 
     if (conn1 != conn2 && conn1 != conn3 && conn2 != conn3) { 
      System.out.println("conn1 != conn2 AND conn1 != conn3 AND conn2 != conn3"); 
      System.out.println("Quod erat demonstrandum"); 
     } 
    } 
} 

輸出

conn1 has the same reference as conn4 
conn1 != conn2 AND conn1 != conn3 AND conn2 != conn3 
Quod erat demonstrandum