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)。
如果有其他的操作行爲不依賴於標籤的值,則吧這些操作變成根類中的具體方法。