Created
June 24, 2014 05:41
-
-
Save Rayer/cc5600f0d177fd8ffd04 to your computer and use it in GitHub Desktop.
CoR in C sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
//CoR in C | |
//這組code可以再多做些什麼呢? | |
//1. 可以替每個handler加上priority | |
//2. 可以改成可變長度list,讓它可以在runtime加 | |
//3. 甚至可以在每次處理以前動態產生一組handler list,可以動態調整 | |
//4. (C++ only)可以做一個模板來compile time產生handler | |
typedef struct _Trouble { | |
int trouble_level; | |
} Trouble; | |
typedef int(*handler)(Trouble*); | |
int handle_minor_trouble(Trouble* t) { | |
if(t->trouble_level < 1) { | |
printf("Minor!\n"); | |
return 1; | |
} | |
printf("Too big trouble %d for Minor!\n", t->trouble_level); | |
return 0; | |
} | |
int handle_medium_trouble(Trouble* t) { | |
if(t->trouble_level < 2) { | |
printf("Medium!\n"); | |
return 1; | |
} | |
printf("Too big trouble for Medium!\n"); | |
return 0; | |
} | |
int handle_major_trouble(Trouble* t) { | |
if(t->trouble_level < 3) { | |
printf("Major!\n"); | |
return 1; | |
} | |
printf("Too big trouble for Major!\n"); | |
return 0; | |
} | |
int handle_catalysm(Trouble* t) { | |
if(t->trouble_level < 4) { | |
printf("Catalysm!\n"); | |
return 1; | |
} | |
printf("Too big trouble for Catalysm!\n"); | |
return 0; | |
} | |
handler handler_list[5] = { | |
handle_minor_trouble, | |
handle_medium_trouble, | |
handle_major_trouble, | |
handle_catalysm, | |
NULL | |
}; | |
void handle_trouble(Trouble* trouble) { | |
for(int i = 0; i < 5; ++i) { | |
if(handler_list[i] == NULL) { | |
printf("It's too late, run for life!"); | |
break; | |
} | |
if((handler_list[i])(trouble)) break; | |
} | |
} | |
int main(int argc, char *argv[]) { | |
Trouble* trouble1 = (Trouble*)malloc(sizeof(Trouble)); | |
Trouble* trouble2 = (Trouble*)malloc(sizeof(Trouble)); | |
trouble1->trouble_level = 2; | |
trouble2->trouble_level = 6; | |
handle_trouble(trouble1); | |
handle_trouble(trouble2); | |
free(trouble1); | |
free(trouble2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment