第20条:类层次优于标签类

来源:互联网 发布:郑州java培训班 编辑:程序博客网 时间:2024/05/21 10:17

标签类代码,一看便知何为标签类。

// 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()方法的冗余。

很显然类层次就优秀很多,就不在赘述了。。。。



0 0
原创粉丝点击