【问题标题】:create interface for different databases, propeties for choice implementation为不同的数据库创建接口,选择实现的属性
【发布时间】:2014-02-01 07:18:21
【问题描述】:

我想为不同的数据库 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);
   }

【问题讨论】:

  • 您需要某种可以读取属性文件、查找并定位“实现”(可能通过 Class.forName)并返回公共接口的实现的管理器
  • 您是否考虑过使用 spring 进行依赖注入?您可以在 spring xml 配置中更改实现。

标签: java sql xml interface


【解决方案1】:

您可以创建 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);
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多