1. 程式人生 > >C語言和設計模式(工廠模式)

C語言和設計模式(工廠模式)

                【 宣告:版權所有,歡迎轉載,請勿用於商業用途。  聯絡信箱:feixiaoxing @163.com】

    工廠模式是比較簡單,也是比較好用的一種方式。根本上說,工廠模式的目的就根據不同的要求輸出不同的產品。比如說吧,有一個生產鞋子的工廠,它能生產皮鞋,也能生產膠鞋。如果用程式碼設計,應該怎麼做呢?

typedef struct _Shoe{    int type;    void (*print_shoe)(struct _Shoe*);}Shoe;
    就像上面說的,現在有膠鞋,那也有皮鞋,我們該怎麼做呢?
void print_leather_shoe(struct _Shoe* pShoe){    assert(NULL != pShoe);    printf("This is a leather show!\n"
);}void print_rubber_shoe(struct _Shoe* pShoe){    assert(NULL != pShoe);    printf("This is a rubber shoe!\n");}
    所以,對於一個工廠來說,建立什麼樣的鞋子,就看我們輸入的引數是什麼?至於結果,那都是一樣的。
#define LEATHER_TYPE 0x01#define RUBBER_TYPE  0x02Shoe* manufacture_new_shoe(int type){    assert(LEATHER_TYPE == type || RUBBER_TYPE == type);    Shoe* pShoe = (Shoe*)malloc
(sizeof(Shoe));    assert(NULL != pShoe);    memset(pShoe, 0, sizeof(Shoe));    if(LEATHER_TYPE == type)    {        pShoe->type == LEATHER_TYPE;        pShoe->print_shoe = print_leather_shoe;    }    else    {        pShoe->type == RUBBER_TYPE;        pShoe->print_shoe = print_rubber_shoe;    }    return
pShoe;}