单件模式算不上什么设计模式。最多也就是个技巧。
typedef struct _Computer {
int type;
} Computer;
void *get_computer( void )
{
static Computer *computer = NULL;
if ( NULL != computer )
return computer;
computer = ( Computer * )malloc( sizeof( Computer ) );
assert( NULL != computer );
return ( void * )computer;
}
主函数如下:
int main( void )
{
Computer *a_computer = get_computer();
a_computer->type = 1;
Computer *b_computer = get_computer();
if ( b_computer != NULL ) {
printf( "%s %d %d\r\n", __FILE__, __LINE__, b_computer->type );
free( b_computer );
b_computer = NULL;
}
}