Skip to content

Instantly share code, notes, and snippets.

@Sixeight
Created June 10, 2009 10:20
Show Gist options
  • Save Sixeight/127136 to your computer and use it in GitHub Desktop.
Save Sixeight/127136 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct PEOPLE {
char name[25];
struct PEOPLE *next;
} people;
struct Greeter {
// methods
struct Greeter* (*say)(void);
struct Greeter* (*hello)(void);
struct Greeter* (*good_bye)(void);
struct Greeter* (*to)(const char*);
struct Greeter* (*and)(const char*);
void (*end)(void);
// fields
char type[14];
people *names;
} *greeter;
void set_type(const char*);
struct Greeter* add_name(const char*);
struct Greeter* hello(void);
struct Greeter* good_bye(void);
void end(void);
struct Greeter* initialize()
{
if (greeter == NULL) {
greeter = (struct Greeter*)malloc(sizeof(struct Greeter));
greeter->say = initialize;
greeter->hello = hello;
greeter->good_bye = good_bye;
greeter->to = add_name;
greeter->and = add_name;
greeter->end = end;
people *root = (people*)malloc(sizeof(people));
root->next = NULL;
greeter->names = root;
}
return greeter;
}
void set_type(const char* type)
{
strcpy(initialize()->type, type);
}
struct Greeter* add_name(const char* name)
{
struct Greeter* gt = initialize();
people *p;
people *new = (people*)malloc(sizeof(people));
strcpy(new->name, name);
new->next = NULL;
for (p = gt->names; p->next != NULL; p = p->next) {}
p->next = new;
return gt;
}
struct Greeter* hello()
{
set_type("hello");
return initialize();
}
struct Greeter* good_bye()
{
set_type("good bve");
return initialize();
}
void end()
{
struct Greeter* gt = initialize();
people *p, *root = gt->names;
if (strcmp(gt->type, "") != 0)
printf("%s, ", gt->type);
for (p = root->next; p->next != NULL; p = root->next) {
printf("%s and ", p->name);
root->next = p->next;
free(p);
}
printf("%s!\n", p->name);
root->next = NULL;
free(p);
strcpy(gt->type, "");
}
int main(int argc, char *argv[])
{
struct Greeter* me = initialize();
me->say()->hello()->
to("yaotti")->
and("satzz")->
and("hmsk")->
end();
me->say()->good_bye()->
to("pole")->
and("umemoto")->
and("muraguchi")->
end();
me->and("tomohiro")->
and("sixeight")->
end();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment