我怎样才能在DB中使用multiton?

时间:2014-01-24 18:35:27

标签: java

数据库(字符表)只能通过实现接口类型IConnection的类访问。 数据库应该是Singleton,但只有具体的连接应该使用它(而不是主函数)。  连接应该是Multitons:在循环法中只有三个由getInstance方法返回(1 2 3 1 2 3 ...)。 客户端(主函数)获取连接对象并使用它来访问数据库。 完成以下代码。在main函数中:获取4个连接并证明它们都使用相同的数据库。  然后证明事实上(尽管有4个初始化引用)只存在3个连接对象。

我无法提供继续...下面的示例代码...

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

1 个答案:

答案 0 :(得分: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