Java 为不同的数据库和属性创建接口以供选择实现
我想为不同的数据库XML、Sql和实现创建接口。我有一个接口,但它对xml很好,但对其他接口好吗?我想从这个接口创建jar库。我还有一本POJO类书,它表示数据库中的对象。我将有两个实现,一个用于XML,一个用于sql,如何在不编译的情况下从属性文件设置一个呢Java 为不同的数据库和属性创建接口以供选择实现,java,sql,xml,interface,Java,Sql,Xml,Interface,我想为不同的数据库XML、Sql和实现创建接口。我有一个接口,但它对xml很好,但对其他接口好吗?我想从这个接口创建jar库。我还有一本POJO类书,它表示数据库中的对象。我将有两个实现,一个用于XML,一个用于sql,如何在不编译的情况下从属性文件设置一个呢 interface DataInterface { public void setBook(ArrayList<Book> book); public ArrayList<Book> getBook();
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);
}
接口数据接口{
公开作废退册(ArrayList书);
公共ArrayList getBook();
公共作废更新(ArrayList book、int行、int列);
公共无效读取();
公开作废新增(图书);
}
您可以创建两个类,即XmlDataInterface
和SqlDataInterface
,这两个类都实现了给定的接口DataInterface
现在,无论您想访问接口在哪里,都可以访问数据接口
,并访问上述所有方法。这样,使用DataInterface
的代码仍然不知道实现细节
当您实例化它时,棘手的部分就会出现。:) 你可以有一个像
your\u file\u name.properties这样的文件,也可以有
DataInterfaceImplementationType=XML(或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);
}
希望这能有所帮助。您需要某种管理器来读取属性文件,查找并定位“实现”(可能通过Class.forName)并返回公共接口的实现您考虑过使用spring进行依赖项注入吗?您可以在SpringXML配置中更改实现。