C语言和设计模式(工厂模式)


工厂模式是比较简单,也是比较好用的一种方式。根本上说,工厂模式的目的就根据不同的要求输出不同的产品。比如说吧,有一个生产鞋子的工厂,它能生产皮鞋,也能生产胶鞋。如果用代码设计,应该怎么做呢?
  1. typedef struct _Shoe  
  2. {  
  3.     int type;  
  4.     void (*print_shoe)(struct _Shoe*);  
  5. }Shoe;  
就像上面说的,现在有胶鞋,那也有皮鞋,我们该怎么做呢?
  1. void print_leather_shoe(struct _Shoe* pShoe)  
  2. {  
  3.     assert(NULL != pShoe);  
  4.     printf("This is a leather show!\n");  
  5. }  
  6.   
  7. void print_rubber_shoe(struct _Shoe* pShoe)  
  8. {  
  9.     assert(NULL != pShoe);  
  10.     printf("This is a rubber shoe!\n");  
  11. }  
所以,对于一个工厂来说,创建什么样的鞋子,就看我们输入的参数是什么?至于结果,那都是一样的。
  1. #define LEATHER_TYPE 0x01   
  2. #define RUBBER_TYPE  0x02   
  3.   
  4. Shoe* manufacture_new_shoe(int type)  
  5. {  
  6.     assert(LEATHER_TYPE == type || RUBBER_TYPE == type);  
  7.   
  8.     Shoe* pShoe = (Shoe*)malloc(sizeof(Shoe));  
  9.     assert(NULL != pShoe);  
  10.   
  11.     memset(pShoe, 0, sizeof(Shoe));  
  12.     if(LEATHER_TYPE == type)  
  13.     {  
  14.         pShoe->type == LEATHER_TYPE;  
  15.         pShoe->print_shoe = print_leather_shoe;  
  16.     }  
  17.     else  
  18.     {  
  19.         pShoe->type == RUBBER_TYPE;  
  20.         pShoe->print_shoe = print_rubber_shoe;  
  21.     }  
  22.   
  23.     return pShoe;  
  24. }  

相关内容