gpt4 book ai didi

design-patterns - DAO/抽象工厂模式——多数据源

转载 作者:行者123 更新时间:2023-12-01 10:07:11 27 4
gpt4 key购买 nike

我目前有一些使用抽象工厂模式设置的 DAO。它看起来像这样:

public abstract class DaoFactory
public static GetDaoFactory()
public abstract IPersonDao GetPersonDao()
// etc.

静态 GetDaoFactory() 返回底层 SqlDaoFactory。直到今天,所有的 Daos 都使用同一个 SQL 数据库。现在,我想向该工厂添加另一个 DAO,但 DAO 将与外部服务而不是 SQL 数据库交互(假设这是 GetCompanyDao())。我基本上只想将此 GetCompanyDao() 方法添加到抽象 DaoFactory 类中,以便公共(public)接口(interface)与底层实现完全分离(不需要/无法判断是否特定的 dao 正在使用 SQL 或外部服务)。

我是否应该简单地将 SqlDaoFactory 重命名为更合适的名称并在其中包含 GetCompanyDao() 方法,以便此 DAO Facotry 现在将 SQL 用于某些 DAO 和外部为对方服务?或者是否有不同的方法来实现此目的?

最佳答案

重命名完全取决于您。 DAO 模式抽象了任何类型的数据访问,不一定是数据库访问。所以你绝对可以继续你的计划。

您可以使用像 spring 这样的框架,而不是手动创建模式。

我只尝试过一次对这些模式进行硬编码。

public abstract class DAOFactory {

// List of DAO types supported by the factory
public static final int MYSQL = 1;
public static final int ORACLE = 2;
public abstract UserDAO getUserDAO() throws SQLException;
public static DAOFactory getDAOFactory(int whichFactory) {

switch (whichFactory) {
case MYSQL:
return new MySQLDAOFactory();
case ORACLE :
......


public class MySQLDAOFactory extends DAOFactory {

public MySQLDAOFactory() {
}
public static final String DRIVER= "/*driver here*/";
public static final String DBURL="/*conn string here*/";
/* instead of using constants you could read them from an external xml file*/

public static Connection createConnection() {
/*create connection object here*/
return conn;
}
public UserDAO getUserDAO() throws SQLException{
return new MySQLUserDAO();
}

public interface UserDAO {
public int insertUser(String fname, String lname);
public ArrayList<User> selectUsers();
}

public class MySQLUserDAO implements UserDAO {

Connection conn=null;
Statement s=null;
public MySQLUserDAO() throws SQLException{
conn = MySQLDAOFactory.createConnection();
s = conn.createStatement();
}

public int insertUser(String fname, String lname)
{
//implementation
}


public ArrayList<User> selectUsers()
{
//implementation
}

关于design-patterns - DAO/抽象工厂模式——多数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9232716/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com