合成复用原则
尽量使用对象组合/聚合,而不是继承关系达到软件复用原则;
聚合 has-a
组合 contains-A
继承 is-A
合成复用原则示例类图
合成复用原则示例代码
public abstract class DBConnection {
public abstract String getConnection();
}
public class MySQLConnection extends DBConnection {
@Override
public String getConnection() {
return "MySQL数据库连接";
}
}
public class PostgreSQLConnection extends DBConnection {
@Override
public String getConnection() {
return "PostgreSQL数据库连接";
}
}
public class ProductDao{
private DBConnection dbConnection;
public void setDbConnection(DBConnection dbConnection) {
this.dbConnection = dbConnection;
}
public void addProduct(){
String conn = dbConnection.getConnection();
System.out.println("使用"+conn+"增加产品");
}
}
public class Test {
public static void main(String[] args) {
ProductDao productDao = new ProductDao();
productDao.setDbConnection(new PostgreSQLConnection());
productDao.addProduct();
}
}
输出:
使用PostgreSQL数据库连接增加产品