Effective Java

来源:互联网 发布:mac虚拟机共享 编辑:程序博客网 时间:2024/06/05 08:06

读书笔记 仅供参考

标签类

一种带有多种风格实例的类
下面这个可以代表圆和矩形

class Figure {    enum Shape {RECTANGLE, CIRCLE};    final Shape shape;    double length;    double width;    double radius;    Figure(double raduis) {        shape = Shape.CIRCLE;        this.radius = raduis;    }    Figure(double width, double length) {        shape = Shape.RECTANGLE;        this.width = width;        this.length = length;    }    double area() {        switch (shape) {            case CIRCLE:                return Math.PI * ( radius * radius);            case RECTANGLE:                return length * width;            default:                throw  new AssertionError();        }    }}

这种类缺点很多,充斥样板代码和条件语句,破坏可读性。
标签类过于冗长,容易出错,并且效率底下。

好的方法

就是采用类层次,即使用继承的方法类重构上面的类。

原创粉丝点击