Create a gist now

Instantly share code, notes, and snippets.

@markd2 /old-days.m
Last active Dec 17, 2015

Embed
What would you like to do?
Drawing Views, violating the open/closed principle.
#import <stdio.h>
// clang -g -Wall -o old-days old-days.m
typedef struct Rect {
int x, y, w, h;
} Rect;
typedef enum {
kButtonView,
kSliderView,
kPonyView
} ViewKind;
typedef struct View {
ViewKind kind;
Rect bounds;
} View;
static void ButtonDraw (View *view) {}
static void SliderDraw (View *view) {}
static void PonyDraw (View *view) {}
void DrawViews (View *views[], int count) {
for (int i = 0; i < count; i++) {
View *view = views[i];
switch (view->kind) {
case kButtonView:
printf ("Drawing a button!\n");
ButtonDraw (view);
break;
case kSliderView:
printf ("Drawing a slider!\n");
SliderDraw (view);
break;
case kPonyView:
printf ("OMG PONIES!\n");
PonyDraw (view);
break;
}
}
} // DrawViews
int main (void) {
View viewsObjects[3] = { { .kind = kButtonView },
{ .kind = kSliderView },
{ .kind = kPonyView } };
View *viewsToDraw[] = { &viewsObjects[0], &viewsObjects[1], &viewsObjects[2] };
DrawViews (viewsToDraw, sizeof(viewsToDraw) / sizeof(*viewsToDraw));
return 0;
} // main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment