日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

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

發(fā)布時間:2024/7/23 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Effective Java~23. 类层次优于标签类 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

標(biāo)簽類,包含一個標(biāo)簽屬性(tag field),表示實(shí)例的風(fēng)格

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

總之,標(biāo)簽類是冗長的,容易出錯的,而且效率低下。

子類型化(subtyping)

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

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

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。