C语言和设计模式(工厂模式)
2011-12-18 10:38
316 查看
【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱: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 0x02 Shoe* 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; }
相关文章推荐
- C语言和设计模式(工厂模式)
- 7、C语言和设计模式(工厂模式)
- C语言和设计模式(工厂模式)【文章都是来自网络,只要自己吸取了就是自己的】
- 20.C语言和设计模式(工厂模式)
- C语言和设计模式(工厂模式)
- C语言和设计模式(工厂模式)06
- C语言和设计模式(工厂模式)
- C语言设计模式-工厂模式
- C语言和设计模式(抽象工厂模式)
- 设计模式——工厂模式(工厂方法)
- C语言设计模式:组合模式
- Java实践之路(设计模式)——工厂模式(抽象工厂)
- php设计模式-工厂模式
- 17、C语言和设计模式(中介者模式)
- 学习:java设计模式—工厂模式
- java设计模式之一工厂模式(Factory Method)
- java设计模式之一工厂模式(Factory Method)
- 设计模式-工厂模式
- 设计模式系列——三个工厂模式(简单工厂模式,工厂方法模式,抽象工厂模式)
- 设计模式 行为模式 命令模式 c语言 版本实现