歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言和設計模式(工廠模式)

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

日期:2017/3/1 10:46:43   编辑:Linux編程
工廠模式是比較簡單,也是比較好用的一種方式。根本上說,工廠模式的目的就根據不同的要求輸出不同的產品。比如說吧,有一個生產鞋子的工廠,它能生產皮鞋,也能生產膠鞋。如果用代碼設計,應該怎麼做呢?
  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. void print_rubber_shoe(struct _Shoe* pShoe)
  7. {
  8. assert(NULL != pShoe);
  9. printf("This is a rubber shoe!\n");
  10. }
所以,對於一個工廠來說,創建什麼樣的鞋子,就看我們輸入的參數是什麼?至於結果,那都是一樣的。
  1. #define LEATHER_TYPE 0x01
  2. #define RUBBER_TYPE 0x02
  3. Shoe* manufacture_new_shoe(int type)
  4. {
  5. assert(LEATHER_TYPE == type || RUBBER_TYPE == type);
  6. Shoe* pShoe = (Shoe*)malloc(sizeof(Shoe));
  7. assert(NULL != pShoe);
  8. memset(pShoe, 0, sizeof(Shoe));
  9. if(LEATHER_TYPE == type)
  10. {
  11. pShoe->type == LEATHER_TYPE;
  12. pShoe->print_shoe = print_leather_shoe;
  13. }
  14. else
  15. {
  16. pShoe->type == RUBBER_TYPE;
  17. pShoe->print_shoe = print_rubber_shoe;
  18. }
  19. return pShoe;
  20. }
Copyright © Linux教程網 All Rights Reserved