Effective Java 学习笔记(20)
来源:互联网 发布:teambition软件下载 编辑:程序博客网 时间:2024/06/05 10:18
类层次要优于标签类。
所谓标签类是指含有多个功能类,如下。
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();
}
}
}
里面即有CIRCLE, 又含有RECTANGLE, 使得结构太复杂,很容易在switch case时少判断了一种情况导致程序出错。不便于维护。而采用类层次结构可以避免这个问题。
// 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; }
}
- Effective Java 学习笔记(20)
- effective java学习笔记
- Effective java学习笔记
- effective java学习笔记
- effective java 学习笔记
- Effective Java 学习笔记
- Effective Java 学习笔记
- Effective Java学习笔记
- Effective Java学习笔记
- Effective Java学习笔记
- Effective Java 学习笔记
- Effective java --学习笔记
- 《Effective Java》学习笔记(1)
- 《Effective Java》学习笔记(3)
- 《Effective Java》学习笔记(4)
- 《Effective Java》学习笔记1
- 《Effective Java》学习笔记2
- 《Effective Java》学习笔记3
- c# windows程序的消息过滤器
- 快速排序
- 背包 锁
- ZOJ 1652 Count the Regions
- MFC实现程序开机自动运行
- Effective Java 学习笔记(20)
- 【转】学习OS历程
- C#.NET 2003中,将DataGrid导出到Excel后,所有的中文显示为乱码
- 操作系统学习要点之我见
- C语言 qsort() 函数
- zoj 2482 IP Address(在水题中学知识,欧耶~)
- String的实现1
- 常用的正则表达式验证类
- 君子爱财,取之有道