2008年6月7日 星期六

CCC

嘗試用C實作了simple factory如下


#include

typedef void (*Method)(void);

typedef struct Interface {
Method method;
} Interface;


void good_method(void)
{
printf("good\n");
}

void bad_method(void)
{
printf("bad\n");
}

Interface* New_Product(char* type)
{
Interface* ret = (Interface*) malloc(sizeof(Interface));
if( strcmp(type, "good") == 0 ) {
ret->method = good_method;
} else if( strcmp(type, "bad") == 0) {
ret->method = bad_method;
} else {
return NULL;
}
return ret;
}

int main(void)
{
Interface* product;
product = New_Product("bad");
product->method();
product = New_Product("good");
product->method();
product = New_Product("bad");
if( product == NULL )
printf("nothing");
else
product->method();

return 0;
}

沒有留言: