优先使用类层次,而不是标签类

优先使用类层次,而不是标签类

概述

标签类是指这样的类:一个类含有两种或者多种风格的实例,这个类包含了一个指明实例风格的标签,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 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);
}
}
}

但这种做法是非常糟糕的,因为这里面包含了枚举声明、标签域,还有switch语句。这里面扩展性很差,并且内存中包含了不必要的占用。

我们应该改换成类层次,定义好抽象类,采用继承的方法实现。