Item 20: Prefer class hierarchies to tagged classes

《类层次优于标签类》
这篇大概意思是说,不要把多种不同风格实例的类放到一个类里用标签区分,那样可读性很差。标签类过于冗余,容易出错,并且效率低下。

要用类的层次继承。层次清晰,不易出错,效率高。

不好的标签类示范:

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

正确的方式是Class hierarchy,:

// 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; }
}
class Square extends Rectangle {
    Square(double side) {
        super(side, side);
    }
}

你可能感兴趣的:(Item 20: Prefer class hierarchies to tagged classes)