(六):处理概括关系
处理概括关系主要是将函数上下移动于继承体系之中。
(1) pull up method 函数上移
有写函数,在各个subclass中产生完全相同的结果或者函数体完全相同
比如在两个subclass中都有createBill()函数
public void createBill(Date date){
double chargeAmount = chargeFor(Date startDate, Date endDate);
addBill();
}
因为chargeFor()函数在每个子类中不同的结果,所以需要在superclass中
public abstract double chargeFor(Date startDate, Date endDate);
把createBill() pull up到supclass中
(2) pull up Constructor body 构造函数上移
你在subclass中拥有一些构造函数,它们的本体代码几乎完全相同
此时在superclass中新建一个构造函数,并在subclass构造函数中调用它
class Manager extends Employee{
pubic Manager(String name, String id, String grade){
this.name = name;
this.id = id;
this.grade = grade;
}
}
替换=》
public class Employee{
protected String name;
protected String id;
public Employee(String name,String id){
this.name = name;
this.id = id;
}
}
class Manager extends Employee{
private String grade;
public Employee(String name, String id, String grade){
super(name,id)
this.grade = grade;
}
}
(3) Replace Inheritance with Delegation 以委托取代继承(适配器模式的雏形)
某个subclass 只使用了subperclass接口中的一部分,或者根本就不需要继承而来的数据。
做法:在subclass中增加一个值域用以保存superclass 调整subclass函数,令它该为委托superclass,然后去掉两者之间的继承关系
比如Vector 的一个子类Statck Statck的两个方法size(),isEmpty()是从Vector继承过来的,其它两个方法push(),pop(),是Statck需要自己声明的
class MyStatck extends Vector{
public void push(Object obj){
insertElementAt(obj,0);
}
public Object pop(){
Object result = firstElement();
removeElementAt(0);
return result;
}
}
替换=》
class MyStatck extends Vector{
Vector vector = new Vector();
public void pop(Object obj){
vector.insertElementAt(obj,0);
}
public Object pop(){
Object result = vector.firstElement();
vector.removeElementAt(0);
return result;
}
//这两个函数是
public int size(){
return vector.size();
}
public boolean isEmpty(){
return vector.isEmpty();
}
}
(4) Replace Delegation with Inheritance以继承取代委托
这个正好和上面Replace Inheritance with Delegation相反,如果发现自己需要使用所托类的所有函数或大部分函数,并且花费很大力气去编写极简的请托函数。
本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-08/105066.htm
