---
title: "类层次优于标签类"
author: "windpoplar"
date: "2016-08-08T20:50:31Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2016-08-08T20:50:31Z"
id: 2316003
url: "https://windpoplar.iteye.com/blog/2316003"
---

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

 

**\[java]** [view plain](http://blog.csdn.net/partner4java/article/details/7397075 "view plain") [copy](http://blog.csdn.net/partner4java/article/details/7397075 "copy")

 

01. // Tagged class - vastly inferior to a class hierarchy!
02. class Figure {
03. enum Shape { RECTANGLE, CIRCLE };
04. // Tag field - the shape of this figure
05. final Shape shape;
06. // These fields are used only if shape is RECTANGLE
07. double length;
08. double width;
09. // 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](http://blog.csdn.net/partner4java/article/details/7397075 "view plain") [copy](http://blog.csdn.net/partner4java/article/details/7397075 "copy")

 

01. // Class hierarchy replacement for a tagged class
02. abstract class Figure {
03. abstract double area();
04. }
05. class Circle extends Figure {
06. final double radius;
07. Circle(double radius) { this.radius = radius; }
08. double area() { return Math.PI * (radius * radius); }
09. }
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. }

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