ITeye博客

类层次优于标签类

windpoplar · 2016-08-08 20:50 · Effective Java · 编程语言 · Markdown

有时候,可能会遇到带有两个甚至更多风格的实例的类,并包含表示实例风格的标签(tag)域。
Demo:

 

[java] view plain copy

 

  1. // Tagged class - vastly inferior to a class hierarchy!
  2. class Figure {
  3. enum Shape { RECTANGLE, CIRCLE };
  4. // Tag field - the shape of this figure
  5. final Shape shape;
  6. // These fields are used only if shape is RECTANGLE
  7. double length;
  8. double width;
  9. // This field is used only if shape is CIRCLE
  10. double radius;
  11. // Constructor for circle
  12. Figure(double radius) {
  13. shape = Shape.CIRCLE;
  14. this.radius = radius;
  15. }
  16. // Constructor for rectangle
  17. Figure(double length, double width) {
  18. shape = Shape.RECTANGLE;
  19. this.length = length;
  20. this.width = width;
  21. }
  22. double area() {
  23. switch(shape) {
  24. case RECTANGLE:
  25. return length * width;
  26. case CIRCLE:
  27. return Math.PI * (radius * radius);
  28. default:
  29. throw new AssertionError();
  30. }
  31. }
  32. }

这些标签类(tagged class)有着许多优点,但是破坏了可读性。
标签类过于冗长、容易出错,并且效率低下。

表示多种风格对象的数据类型:子类型化(subtyping)。标签类正是类层次的一种简单的仿效。
Demo:

[java] view plain copy

 

  1. // Class hierarchy replacement for a tagged class
  2. abstract class Figure {
  3. abstract double area();
  4. }
  5. class Circle extends Figure {
  6. final double radius;
  7. Circle(double radius) { this.radius = radius; }
  8. double area() { return Math.PI * (radius * radius); }
  9. }
  10. class Rectangle extends Figure {
  11. final double length;
  12. final double width;
  13. Rectangle(double length, double width) {
  14. this.length = length;
  15. this.width  = width;
  16. }
  17. double area() { return length * width; }
  18. }
  19. class Square extends Rectangle {
  20. Square(double side) {
  21. super(side, side);
  22. }
  23. }

标签类很少有适用的时候。当你想要编写一个包含显示标签域类时,应该考虑一下,这个标签是否可以被取消,这个类是否可以用类层次来代替。当你遇到一个包含标签与的现有类时,就要考虑将它重构到一个层次结构中去。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。