//C 没有接口:用函数指针表充当接口
typedef struct Shape Shape;
//接口:每种形状都能做什么
struct ShapeOps {
const char *name;
double (*area)(const Shape *self);
void (*scale)(Shape *self, double factor);
};
//对象只保存指向其类型的表的指针:
//这张表对所有对象是同一张,且永不改变
struct Shape {
const struct ShapeOps *ops;
};
//接口的唯一实现
typedef struct {
Shape base;
double width, height;
} Rect;
double rectArea(const Shape *self) {
const Rect *rect = (const Rect *)self;
return rect->width * rect->height;
}
void rectScale(Shape *self, double factor) {
Rect *rect = (Rect *)self;
rect->width *= factor;
rect->height *= factor;
}
const struct ShapeOps rectOps = {"rect", rectArea, rectScale};
Rect rect = {{&rectOps}, 2, 3};
//下面的代码只看到 Shape 及其表
Shape *shape = &rect.base;
double area1 = shape->ops->area(shape);
//area1 is 6
shape->ops->scale(shape, 2);
double area2 = shape->ops->area(shape);
//area2 is 24
const char *name = shape->ops->name;
//name is "rect"
//表可以增长,对象仍然只持有一个指针
bool onePointer = sizeof(Shape) == sizeof(void *);
//onePointer is true
printf("area1 is %g\n", area1);
printf("area2 is %g\n", area2);
printf("name is %s\n", name);
printf("onePointer is %s\n", onePointer ? "true" : "false");