Skip to content

Instantly share code, notes, and snippets.

@markd2
Last active December 17, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markd2/5629516 to your computer and use it in GitHub Desktop.
Save markd2/5629516 to your computer and use it in GitHub Desktop.
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