我正在学习有关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的答案有很好的解释。

可以在此处使用Singleton模式。但是,它使CustomerDAO与DatabaseManager紧密耦合。

最好定义DatabaseManager的接口:

public interface DatabaseManager {
    public Connection getConnectionObject();
}

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


然后,可以通过setter方法或构造函数将DatabaseManager实现注入到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... ");
    }

}

07-26 03:53