Item 22: Use interfaces only to define types[接口只用与定义类型]
Item23: Prefer Class hierachies to tagged Class
Tagged Class:带有标签的类,类似于将明明是继承关系的类,糅杂在一个类中用组合的形式表现
这种情形会造成一些恶果让代码更难以维护:
反例:
// 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(shape);
}
}
}
正例:
// 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;
}
@Override
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;
}
@Override
double area() {
return length * width;
}
}
本质上意在围绕:设计模式的一些基本原则
-
单一职责:类的职责需要单一,如果不够单一类中就会出现Tagged Class等一些硬编码的情况发生,可扩展性差,代码耦合度高
-
开闭原则:面对修改关闭但是对扩展开放,既是可以对类和方法的改变可以扩展