gpt4 book ai didi

java - 继承DatabaseManager类或使其成为单例对象来实现DAO模式哪个更好?为什么?

转载 作者:行者123 更新时间:2023-12-01 22:45:32 24 4
gpt4 key购买 nike

我正在学习 SRP,并且必须减少客户对象的责任,因为该对象包含太多信息。所以我把它变成了一个 Pojo 并提取了数据库逻辑。我试图找到最适合此设置的设计,并在使 DatabaseManager 类成为父类或可以返回单个连接对象的单例之间进行划分。该系统将用于在数据库中插入和删除客户。我不希望我的域对象/DAO 担心连接详细信息。我目前的设计是否强烈遵循 OOP 设计原则?

public class DatabaseManager {

private Connection conn;

private static DatabaseManager managerInstance = new DatabaseManager();

private DatabaseManager() {

}

public static DatabaseManager getInstance() {
return managerInstance;
}

/**
* contains connection details
*
* @throws SQLException
*/
public void connect() throws SQLException {
System.out.println("Established Database Connection...");
conn = DriverManager.getConnection("Some/Database/URL");
}

public Connection getConnectionObject() {
return conn;
}

public void disconnect() throws SQLException {
conn.close();
System.out.println("Disconnected from Database...");
}
}

这是客户对象:

public class Customer {

private int id;
private String name;
private boolean active;


public Customer(int id, String name, String department, boolean working) {
super();
this.id = id;
this.name = name;
this.department = department;
this.working = working;
}

@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", department="
+ department + ", working=" + working + "]";
}
}

客户 DAO:

public class CustomerDAO {

public CustomerDAO() {
}

public void addCustomer(Customer Customer) throws SQLException {
DatabaseManager.getInstance().getConnectionObject().prepareStatement("some sql... ");
}

public void removeCustomer(Customer Customer) throws SQLException {
DatabaseManager.getInstance().getConnectionObject().prepareStatement("some sql... ");
// implementation details avoided
}

}

最佳答案

恕我直言,继承和单例都不是最好的设计。

继承是为了建模“is-a”。 CustomerDAO 不是 DatabaseManager,并且您不希望将 DatabaseManager 的功能公开给 CustomerDAO 的客户端,因此您不应该使用继承。这个question的答案中有一个很好的解释。

这里使用单例模式是可以的。然而,它使得 CustomerDAO 与 DatabaseManager 紧密结合。

最好定义DatabaseManager的接口(interface):

public interface DatabaseManager {
public Connection getConnectionObject();
}

public class DatabaseManagerImpl implements DatabaseManager {
// ...
}

然后可以通过setter方法或构造函数将DatabaseManager实现注入(inject)到DAO中。

public class CustomerDAO {

private DatabaseManager databaseManager;

public void setDatabaseManager(DatabaseManager databaseManager) {
this.databaseManager = databaseManager;
}

public void addCustomer(Customer Customer) throws SQLException {
databaseManager.getConnectionObject().prepareStatement("some sql... ");
}

}

关于java - 继承DatabaseManager类或使其成为单例对象来实现DAO模式哪个更好?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25439154/

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