Effective Java 学习笔记(20)

来源:互联网 发布:teambition软件下载 编辑:程序博客网 时间:2024/06/05 10:18

类层次要优于标签类。

 

所谓标签类是指含有多个功能类,如下。

 

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();
   }
  }
 }

 

 

里面即有CIRCLE, 又含有RECTANGLE, 使得结构太复杂,很容易在switch case时少判断了一种情况导致程序出错。不便于维护。而采用类层次结构可以避免这个问题。

 

 

// Class hierarchy replacement for a tagged class
abstract class Figure {
abstract double area();
}
class Circle extends Figure {
final double radius;
Circle(double radius) { this.radius = radius; }
double area() { return Math.PI * (radius * radius); }
}

 

class Rectangle extends Figure {
final double length;
final double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double area() { return length * width; }
}

原创粉丝点击