2013-10-14 :-)
_ [C][デザインパターン][Commandパターン]C で Command パターン
安直な queue とか書いてみると実現出来るかしら。queue というかリングバッファになってるけど。
/*
Command パターン的な
*/
#include <stdio.h>
#include <stdarg.h>
#define QUEUE_MAX 4
typedef void (*command)(int argc, ...);
command queue[QUEUE_MAX];
int start_index;
int end_index;
void enqueue(command cmd)
{
if(queue[end_index] != NULL)
{
printf("queue is full\n");
return;
}
queue[end_index] = cmd;
end_index++;
if(end_index >= QUEUE_MAX)
{
end_index = 0;
}
}
command dequeue(void)
{
command cmd;
cmd = queue[start_index];
queue[start_index] = NULL;
start_index++;
if(start_index >= QUEUE_MAX)
{
start_index = 0;
}
return cmd;
}
void initialize(void)
{
int i;
for(i = 0; i < QUEUE_MAX; i++)
{
queue[i] = NULL;
}
start_index = 0;
end_index = 0;
}
void command1(int argc, ...)
{
int i;
va_list args;
va_start(args, argc);
printf("command1\n");
for(i = 0; i < argc; i++)
{
int n;
n = va_arg(args, int);
printf("%d\n", n);
}
va_end(args);
}
void command2(int argc, ...)
{
int i;
va_list args;
va_start(args, argc);
printf("command2\n");
for(i = 0; i < argc; i++)
{
int n;
n = va_arg(args, int);
printf("%d\n", n);
}
va_end(args);
}
void test_queue(void)
{
int i;
printf("test_queue start\n");
initialize();
enqueue(command1);
enqueue(command2);
for(i = 0; i < 16; i++)
{
command v = dequeue();
if(v != NULL)
{
v(1, i);
}
}
printf("test_queue end\n");
}
int main(int ac, char** av)
{
test_queue();
return 0;
}
test_queue start command1 0 command2 1 test_queue end
_ [C][デザインパターン][Observerパターン]C で Observer パターン
Command パターンと同じようなもんで。ううん
/*
Observer パターン的な
*/
#include <stdio.h>
#include <stdarg.h>
#define OBSERVER_MAX 4
typedef void (*observer)(int argc, ...);
observer observers[OBSERVER_MAX];
int end_index;
void register_observer(observer o)
{
if(end_index >= OBSERVER_MAX)
{
printf("queue is full\n");
return;
}
observers[end_index] = o;
end_index++;
}
void notify_observer(void)
{
int i;
for(i = 0; i < end_index; i++)
{
observer o = observers[i];
if(o != NULL)
{
o(1, i);
}
}
}
void initialize(void)
{
int i;
for(i = 0; i < OBSERVER_MAX; i++)
{
observers[i] = NULL;
}
end_index = 0;
}
void update1(int argc, ...)
{
int i;
va_list args;
va_start(args, argc);
printf("update1\n");
for(i = 0; i < argc; i++)
{
int n;
n = va_arg(args, int);
printf("%d\n", n);
}
va_end(args);
}
void update2(int argc, ...)
{
int i;
va_list args;
va_start(args, argc);
printf("update2\n");
for(i = 0; i < argc; i++)
{
int n;
n = va_arg(args, int);
printf("%d\n", n);
}
va_end(args);
}
void test_observer(void)
{
printf("test_observer start\n");
initialize();
register_observer(update1);
register_observer(update2);
notify_observer();
printf("test_observer end\n");
}
int main(int ac, char** av)
{
test_observer();
return 0;
}
test_observer start update1 0 update2 1 test_observer end
[ツッコミを入れる]






