Effective Java~23. 类层次优于标签类
生活随笔
收集整理的這篇文章主要介紹了
Effective Java~23. 类层次优于标签类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
標簽類,包含一個標簽屬性(tag field),表示實例的風格
// Tagged class - vastly inferior to a class hierarchy! class Figure {enum Shape { RECTANGLE, CIRCLE };// Tag field - the shape of this figurefinal Shape shape;// These fields are used only if shape is RECTANGLEdouble length;double width;// This field is used only if shape is CIRCLEdouble radius;// Constructor for circleFigure(double radius) {shape = Shape.CIRCLE;this.radius = radius;}// Constructor for rectangleFigure(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);}} }總之,標簽類是冗長的,容易出錯的,而且效率低下。
子類型化(subtyping)
首先定義一個包含抽象方法的抽象類,該標簽類的行為取決于標簽值。
接下來,為原始標簽類的每種類型定義一個根類的具體子類。
總結
以上是生活随笔為你收集整理的Effective Java~23. 类层次优于标签类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Data JPA 从入门到
- 下一篇: Java加密与解密的艺术~SM4实现