第20條:類層次優於標籤類

來源:互聯網
上載者:User

有時候,可能會遇到帶有兩個甚至更多風格的執行個體的類,並包含表示執行個體風格的標籤(tag)域。
Demo:

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

這些標籤類(tagged class)有著許多優點,但是破壞了可讀性。
標籤類過於冗長、容易出錯,並且效率低下。

表示多種風格對象的資料類型:子類型化(subtyping)。標籤類正是類層次的一種簡單的仿效。
Demo:

// Class hierarchy replacement for a tagged classabstract class Figure {    abstract double area();}class Circle extends Figure {    final double radius;    Circle(double radius) { this.radius = radius; }    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;    }    double area() { return length * width; }}class Square extends Rectangle {    Square(double side) {        super(side, side);    }}

標籤類很少有適用的時候。當你想要編寫一個包含顯示標籤域類時,應該考慮一下,這個標籤是否可以被取消,這個類是否可以用類層次來代替。當你遇到一個包含標籤與的現有類時,就要考慮將它重構到一個階層中去。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.