C中的对象工厂而不是C++

Ste*_*rst 0 c c++ design-patterns

我正在将一堆代码从C++转换为C. C对象工厂中是否存在等效模式?

请考虑以下源代码.基于参数(int type),ObjectFactory()函数应该返回一个指向修脚类型结构的void指针.如何以函数返回后可以指向它的方式实例化结构.

typedef struct {
    unsigned int a; 
    unsigned int b; 
    unsigned int c; 
} CThings ; 

typedef struct {
    unsigned int d; 
    unsigned int e; 
    unsigned int f; 
} CPlaces ; 

void * ObjectFactory( int type ) {

    switch( type ) {
        case 5 : {          
            return ??? CPlaces ; 
            break; 
        }
        case 35 : {         
            return ??? CThings ; 
            break; 
        }
        default: {
            // unknown type 
            return NULL ; 
        }
    }

    return NULL ; 
}



int _tmain(int argc, _TCHAR* argv[])
{
    void * p = ObjectFactory( 5 ); 

    // Do soemthing with the pointer. 
    CPlaces * places = (CPlaces*) p ; 

    places->d = 5 ; 
    places->e = 6 ; 
    places->f = 7 ; 


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 5

如何使用malloc:

case 5: return malloc(sizeof(struct CPlaces));
Run Code Online (Sandbox Code Playgroud)

break如果你已经回来,就不需要了.如果您愿意,可以在返回之前添加一些初始化.

调用者必须知道实际类型,以便她可以将指针转换回正确的类型.这可能相当于调用者站点上的重复switch语句.