日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Effective Java~23. 类层次优于标签类

發布時間:2024/7/23 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)

首先定義一個包含抽象方法的抽象類,該標簽類的行為取決于標簽值。
接下來,為原始標簽類的每種類型定義一個根類的具體子類。

// 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; } }

總結

以上是生活随笔為你收集整理的Effective Java~23. 类层次优于标签类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。