1.标签类
标签类是指在类中定义了一个变量,使用该变量的值来控制该做什么动作。
2.标签类(不推荐)
能够表示圆形或矩形的类:
public class Figure { enum Shape {RECTANGLE, CIRCLE}; final Shape shape; double length; double width; double radius; Figure(double radius) { shape = Shape.CIRCLE; this.radius = radius; } Figure(double length, double width) { shape = Shape.RECTANGLE; this.length = length; this.width = width; } double area() { switch (shape) { case RECTANGLE: return length * width; break; case CIRCLE: return Math.PI * (radius * radius); break; default: throw new AssertionError(); } }}
标签类过于冗长、容易出错,并且效率低下。
3.类层次(推荐)
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; }}