标签类代码,一看便知何为标签类。
// Tagged class - vastly inferior to a class hierarchy!
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();
}
}
}
代码中Shape shape就定义了一个枚举类型的标签,用于表示Figure类属于那种形状。
标签类缺点:对于同一种形状的对象来说,Figure类的代码中就存在冗余的代码。如:构造器的冗余,area()方法的冗余。
很显然类层次就优秀很多,就不在赘述了。。。。