2.0 - Design Patterns seven principles of software architecture design - synthesis multiplexing principle

Synthesis of multiplexing principles (Composite / Aggregate Reuse Principle, CARP) refers to the possible object composition (has-a) / polymerized (contanis-a), instead of inheritance purposes of software reuse. You can make the system more flexible, to reduce the coupling between the class and class, a relatively small change in the influence of other classes class caused. Our inheritance is called white-box reuse, which is equivalent to all of the implementation details are exposed to the subclass. Composition / polymerization also known as black box multiplexed objects can not be accessed outside the class implementation details. To do code design based on specific business scenarios, in fact, we need to follow OOP model. Or in database operations, for example, to create the first DBConnection categories:

public class DBConnection {
   public String getConnection(){
    return "MySQL 数据库连接";
   }
}

Creating ProductDao categories:

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+"增加产品");
	}
}

This is a very typical synthesis multiplexing principle scenarios. However, the current designs, DBConnection is not an abstraction, not easy system expansion. The current system supports the MySQL database connection, assuming that business changes, database operations to support Oracle database layer. Of course, we can add support for Oracle database method in DBConnection in. But contrary to the principle of opening and closing. In fact, we do not have to modify the code Dao, DBConnection will modify the abstract, look at the code:

public abstract class DBConnection {
	public abstract String getConnection();
}

Then, the logic pulled MySQL:

public class MySQLConnection extends DBConnection {
    @Override
    public String getConnection() {
   		 return "MySQL 数据库连接";
    }
}

Oracle re-create the logical support of:

public class OracleConnection extends DBConnection {
    @Override
    public String getConnection() {
    	return "Oracle 数据库连接";
    }
}

The particular choice to the application layer, look class diagram:

to sum up

Learning design principles, learning the basic design patterns. In the actual development process, not necessarily require that all the code follows the design principle, we have to consider manpower, time, cost, quality, not deliberately pursuit of perfection, to follow the design principles in appropriate scene, embodies a kind of trade-offs, help us design a more elegant code structure.

Guess you like

Origin blog.csdn.net/madongyu1259892936/article/details/93632075