7、C语言和设计模式(工厂模式)
2015-08-04 22:02
597 查看
工厂模式是比较简单,也是比较好用的一种方式。根本上说,工厂模式的目的就根据不同的要求输出不同的产品。比如说吧,有一个生产鞋子的工厂,它能生产皮鞋,也能生产胶鞋。如果用代码设计,应该怎么做呢?
[cpp]
view plaincopy
typedef struct _Shoe
{
int type;
void (*print_shoe)(struct _Shoe*);
}Shoe;
就像上面说的,现在有胶鞋,那也有皮鞋,我们该怎么做呢?
[cpp]
view plaincopy
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");
}
所以,对于一个工厂来说,创建什么样的鞋子,就看我们输入的参数是什么?至于结果,那都是一样的。
[cpp]
view plaincopy
#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;
}
[cpp]
view plaincopy
typedef struct _Shoe
{
int type;
void (*print_shoe)(struct _Shoe*);
}Shoe;
就像上面说的,现在有胶鞋,那也有皮鞋,我们该怎么做呢?
[cpp]
view plaincopy
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");
}
所以,对于一个工厂来说,创建什么样的鞋子,就看我们输入的参数是什么?至于结果,那都是一样的。
[cpp]
view plaincopy
#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/C++语言》 林锐 韩永泉编著 总结3
- 什么是c++中的多态
- 6、C语言和设计模式(之模板模式)
- C++学习
- [C++学习笔记]--常量对象、常量成员函数和常引用
- [C++学习笔记]--友元、this指针
- C++ explicit 关键字
- 《高质量程序设计指南C/C++》 林锐 韩永泉编著 总结2
- C语言及程序设计进阶例程-39 银行储蓄系统(第六版)开发
- C++语言中的四种类型转换
- C++语言中的四种类型转换
- hdoj2191多重背包化为01背包
- 一起talk C栗子吧(第三十一回:C语言实例--常用排序算法总结)
- C++中的智能指针
- C++ 的Vector增长方式
- C++STL二分查找函数集及补充
- 【effective c++读书笔记】【第5章】实现(1)
- 【effective c++读书笔记】【第5章】实现(1)
- [C++学习笔记]--成员对象和封闭类
- const成员函数和构造函数