原创文章,如有转载,请注明出处:http://blog.csdn.net/yihui823/article/details/6932952
把一段代码,业务逻辑剥离后,给大家看看。
基类:
package testjava;
/**
* 书的基类
*/
public class BaseBook {
private int type = -1;
public BaseBook(int type) {
this.type = type;
}
/**
* 打印页面
*/
public void printPage() {
if (type == 1) {
System.out.println("Print with the green color.");
} else if (type == 2) {
System.out.println("Print with the blue color.");
} else {
System.out.println("Print with the white color.");
}
}
}
子类1:
package testjava;
/**
* 绿色的书
*/
public class GreenBook extends BaseBook {
public GreenBook(int type) {
super(type);
}
/**
* 得到颜色
* @return 颜色
*/
public String getColor() {
return "Green";
}
}
子类2:
package testjava;
/**
* 蓝色的书
*/
public class BlueBook extends BaseBook {
public BlueBook(int type) {
super(type);
}
/**
* 得到颜色
* @return 颜色
*/
public String getColor() {
return "Blue";
}
}
调用的类:
package testjava;
/**
* 执行类
*/
public class Testjava {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
BlueBook bb = new BlueBook(2);
bb.printPage();
GreenBook gb = new GreenBook(1);
gb.printPage();
}
}
运行结果当然是对的。可是,子类的行为,却定义在了父类之中了。也就是说,基类的“书”,却根据每本书的颜色去做行为判断的。
if (type == 1) {
System.out.println("Print with the green color.");
} else if (type == 2) {
System.out.println("Print with the blue color.");
} else {
System.out.println("Print with the white color.");
}
这个结构,扩展性不好,也不好维护,也不好阅读。
问当事人,当事人说,我在父类没法知道是哪个子类啊。但是这个业务是可以抽取的,所以就写成这个样子了。
其实,可以这么写的。
基类:
package testjava.right;
/**
* 书的基类
*/
public abstract class BaseBook {
public abstract String getColor();
/**
* 打印页面
*/
public void printPage() {
System.out.println("Print with the " + getColor() + " color.");
}
}
子类1:
package testjava.right;
/**
* 蓝色的书
*/
public class BlueBook extends BaseBook {
/**
* 得到颜色
* @return 颜色
*/
public String getColor() {
return "Blue";
}
}
子类2:
package testjava.right;
/**
* 绿色的书
*/
public class GreenBook extends BaseBook {
/**
* 得到颜色
* @return 颜色
*/
public String getColor() {
return "Green";
}
}
执行类:
package testjava.right;
/**
* 执行类
*/
public class Testjava {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
BlueBook bb = new BlueBook();
bb.printPage();
GreenBook gb = new GreenBook();
gb.printPage();
}
}
把属于子类的行为,定义成抽象函数,由子类去实现。OK