一、基本介绍
-
Composite/Aggregate Reuse Principle,组合/聚合复用原则
- Classes may achieve polymorphic behavior and code reuse by containing other classes which implement the desired functionality instead of through inheritance.(类可以通过包含其他实现所需功能的类而不是通过继承实现多态行为和代码重用)
- 多用组合,少用继承
- 组合/聚合复用原则就是在一个新的对象里面使用一些已有的对象,使之成为新对象的一部分;新的对象通过向这些对象的委派达到复用已有功能的目的(重用机制——委派)
- Classes may achieve polymorphic behavior and code reuse by containing other classes which implement the desired functionality instead of through inheritance.(类可以通过包含其他实现所需功能的类而不是通过继承实现多态行为和代码重用)
-
一般来说,组合/聚合比继承好
- For reusing
- Aggregation/Composition is “black box” reusing(黑盒复用), the details of contained object is invisible for clients.
- Inheritance is “white box” reusing(白盒复用), strong coupling, the code is reused statically
- For polymorphism
- Aggregation/Composition is flexible polymorphism for not only implementations but also abstractions.
- Inheritance is fixed. The interfaces (implementing rules) are fixed. Only implementations is extendable.
- For reusing
二、一个栗子:
1. CRP reuse
- JDK container:Stack<E> 继承 Vector<E>
- 利用组合聚合实现简易 Stack<E>
package crp;
import java.io.Serializable;
import java.util.Stack;
import java.util.Vector;
/**
* @author 32098
*/
public class MyStack<E> implements Serializable {
private final Vector<E> vector;
public MyStack(Vector<E> vector){
this.vector = vector;
}
public E push(E item){
vector.addElement(item);
return item;
}
public E pop(){
E obj = peek();
vector.removeElementAt(vector.size()-1);
return obj;
}
public E peek(){
return vector.elementAt(vector.size()-1);
}
public boolean empty(){
return vector.size() == 0;
}
public int search(Object o){
int i = vector.lastIndexOf(o);
if (i >= 0){
return vector.size()-i;
}
return -1;
}
private static final long serialVersionUID = 1224463164541339165L;
}
2. CRP polymorphic
- No CRP
package crp.a;
/**
* @author 32098
*/
public class Employee {
public void doWork(){
}
}
package crp.a;
/**
* @author 32098
*/
public class Manager extends Employee{
@Override
public void doWork(){
// manager work
}
}
package crp.a;
/**
* @author 32098
*/
public class Worker extends Employee{
@Override
public void doWork(){
// worker work
}
}
- CRP
package crp.b;
/**
* @author 32098
*/
public interface Role {
/**
* do work
*/
public void doWork();
}
package crp.b;
/**
* @author 32098
*/
public class Manager implements Role {
@Override
public void doWork(){
// manager work
}
}
package crp.b;
/**
* @author 32098
*/
public class Worker implements Role {
@Override
public void doWork(){
// worker work
}
}
package crp.b;
/**
* @author 32098
*/
public class Employee {
private final Role role;
public Employee(Role role){
this.role = role;
}
public void doWork(){
role.doWork();
}
}
package crp.b;
/**
* @author 32098
*/
public class Main {
public static void main(String[] args) {
Role role = new Manager();
Employee employee = new Employee(role);
employee.doWork();
}
}