EffectiveJava之19-用類層次代替聯合

1、  C中的聯合體:

typedef  enum {RECT , CIRC} shape_type

 

typedef  struct {

       double length;

       double width;

}rectangleDimensions_t

      

typedef  struct {

       double radius;

}circle Dimensions_t

 

typedef  struct {

       shape_type tag ;

       union {

           rectangleDimensions_t   rectangle ;

              circle Dimensions_t circle ;

}dimensions

       } shape_t

 

 

       double area ( shape_t * pshape_t ){

              switch( pshape_t ->tag){

              case RECT : {

                     double length = pshape_t-> dimensions . rectangle .length ;

                     double width = pshape_t-> dimensions . rectangle .width ;

                     return           l* w ;

}

           CaseCIRC : {

           double  r = pshape_t-> dimensions . circle.radius;

              return           r*r*Pi;

 

           }

           Default: return -1;

  

      把一個可區分的聯合變換爲一個類層次:

      先定義一個抽象類,每個操作定義一個抽象方法,其行爲取決去便籤的值。

      如上例:  area 這個首相類的類層次的根(root)。

                 如果有其他的操作行爲不依賴於標籤的值,則吧這些操作變成根類中的具體方法。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章