簡體   English   中英

為不同的數據庫創建接口,選擇實現的傾向

[英]create interface for different databases, propeties for choice implementation

我想為不同的數據庫XML,Sql和實現創建接口。 我有一個接口,但對xml很好,但對其他接口呢? 我想從此接口創建jar庫。 我還有一個POJO類Book,它表示數據庫中的對象。 我將有兩種實現,一種用於XML,一種用於sql,如何在不進行編譯的情況下從屬性文件中設置一種?

 interface DataInterface {

public void setBook(ArrayList<Book> book);

public ArrayList<Book> getBook();

public void update(ArrayList<Book> book, int row, int col);

public void read();

public void add(Book book);
   }

您可以創建2個類,即XmlDataInterfaceSqlDataInterface ,這兩個類都實現了給定的接口DataInterface

現在,無論您想訪問該接口的什么地方,都可以引用DataInterface ,並可以訪問上述所有方法。 這樣,使用DataInterface的代碼仍不了解實現細節。


棘手的部分是在您實例化它時出現的。 :)

您可以擁有一個諸如your_file_name.properties類的文件,並具有諸如

DataInterfaceImplementationType = XML(OR SQL)

存儲在其中。

您可以輕松地將其作為鍵值對進行訪問(有關詳細信息,請參閱java.util.Properties)。

現在唯一剩下的就是實際的實例化,應該類似於

DataInterface dataInterface; // Declare as a member.
// Use it everywhere freely without worrying.


// In maybe a constructor put following.

String dataInterfaceImplementationValue;

// Code to read properties file and get value of dataInterfaceImplementationValue.

if (dataInterfaceImplementationValue.equals("XML")) {
    dataInterface = new XmlDataInterface();
} else if (dataInterfaceImplementationValue.equals("SQL") {
    dataInterface = new SqlDataInterface();
} else {
    System.out.println("Invalid property set: " + dataInterfaceImplementationValue);
}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM