Last active
December 13, 2015 18:09
-
-
Save neuro-sys/4953620 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /* http://adampetersen.se/Patterns%20in%20C%201.pdf | |
| * http://adampetersen.se/Patterns%20in%20C%202,%20STATE.pdf | |
| * http://www.adampetersen.se/Patterns%20in%20C%203,%20STRATEGY.pdf | |
| * http://www.adampetersen.se/Patterns%20in%20C%204,%20OBSERVER.pdf | |
| * http://www.adampetersen.se/Patterns%20in%20C%205,%20REACTOR.pdf | |
| */ | |
| #include <stdio.h> | |
| #include <string.h> | |
| #include <stdlib.h> | |
| struct IAnimal { | |
| void (*eat)(int food); | |
| void (*sleep)(int secs); | |
| }; | |
| struct Cat { | |
| struct IAnimal _base; | |
| void (*meow)(void); | |
| }; | |
| void cat_eat(int food) { printf("%s: %d\n", __func__, food); }; | |
| void cat_sleep(int secs) { printf("%s: %d\n", __func__, secs); }; | |
| void cat_meow(void) { printf("%s: meow!\n", __func__); }; | |
| struct Cat* CreateACat(void) { | |
| struct Cat* x = malloc(sizeof (struct Cat)); | |
| x->_base.eat = cat_eat; | |
| x->_base.sleep = cat_sleep; | |
| x->meow = cat_meow; | |
| return x; | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| struct IAnimal* pa = (struct IAnimal*) CreateACat(); | |
| pa->eat(42); | |
| ((struct Cat*) pa)->meow(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment