有時候,可能會遇到帶有兩個甚至更多風格的執行個體的類,並包含表示執行個體風格的標籤(tag)域。
Demo:
// 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(); } }}
這些標籤類(tagged class)有著許多優點,但是破壞了可讀性。
標籤類過於冗長、容易出錯,並且效率低下。
表示多種風格對象的資料類型:子類型化(subtyping)。標籤類正是類層次的一種簡單的仿效。
Demo:
// Class hierarchy replacement for a tagged classabstract 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); }}
標籤類很少有適用的時候。當你想要編寫一個包含顯示標籤域類時,應該考慮一下,這個標籤是否可以被取消,這個類是否可以用類層次來代替。當你遇到一個包含標籤與的現有類時,就要考慮將它重構到一個階層中去。