Skip to content

Instantly share code, notes, and snippets.

@btc
Created January 30, 2014 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save btc/8703826 to your computer and use it in GitHub Desktop.
Save btc/8703826 to your computer and use it in GitHub Desktop.
Observers in C
/* observed component */
typedef struct
{
int listener_count;
/* array of function pointers */
void (*listener_list[10])(unsigned,unsigned);
} Button;
void button_Init( Button *pButton )
{
pButton->listener_count = 0;
}
void button_RemoveClickListener( Button *pButton,
void (*fp)(unsigned,unsigned) )
{
unsigned i;
void (*temp)(unsigned,unsigned);
for( i = 0; i < pButton->listener_count; ++i )
{
if( pButton->listener_list[i] == fp )
{
pButton->listener_count--;
pButton->listener_list[i] =
pButton->listener_list[pButton->listener_count];
}
}
}
void button_AddClickListener( Button *pButton,
void (*fp)(unsigned,unsigned) )
{
button_RemoveClickListener( pButton, fp );
pButton->listener_list[ pButton->listener_count++ ] = fp;
}
void button_Click( Button *pButton, unsigned x, unsigned y )
{
unsigned i;
for( i = 0; i < pButton->listener_count; ++i )
{
pButton->listener_list[i](x,y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment