|
所谓标签类,就是一些…你往下看,看着看着就明白了。O(∩_∩)O~不过,你要记住,它不是个什么好东西。
直接上一个例子:
class Figure {
enum Shape {RECTANGLE, CIRCLE} ;
// Tag field - the shape of this figure
final Shape shape;
// These fields are used only if shape is RECTANGLE
double length;
double width;
// This field is used only if shape is CIRCLE
double radius;
// Constructor for circle
Figure(double radius) {
shape = Shape.CIRCLE;
this.radius = radius;
}
// Constructor for rectangle
Figure(double length, double width) {
shape = Shape.RECTANGLE;
this.length = length;
this.width = width;
}
double area() {
switch (shape) {
case RECTANGLE:
return length * width;
case CIRCLE:
return Math.PI * (radius * radius);
default:
throw new AssertionError();
}
}
}
这个类是要做什么呢?Figure中有两中图形:RECTANGLE, CIRCLE.它们有着各自的构造,但是公用一个计算面积的area()方法,在方法中通过判断来执行不同的判断方法。
那么,问题来了,如果我再添加一个三角形,你该怎么办?能解决?那要是再添加一个梯形呢?…
其实这本来是个很简单的问题,采用多态的解决方案就可以了。但是,假如你按照上面这种方法解决的话,类中会充满各种用于区别不同情况的标签,枚举、条件语句等。这样一来,程序的可读性就会大大降低,并且不容易拓展。
所以,我们在写代码的时候一定要注意类的层次,不要随便堆砌代码,清晰明了的类层次关系是防止代码腐烂的有效前提。
我的博客原文:http://www.xubitao.cn/blog/2014/10/13/prefer-class-hierarchies-to-tagged-classes/ |