前言,对于工厂模式理解一直停留在表面上,包括我在写这篇文章时,理解也不是很深刻,但寥胜于无,简单写一下自己目前的理解,等以后有了更多的心得再回来更新一下吧;)
工厂模式:通过专门定义一个工厂类来负责创建其他类的实例,被创建的类需要有共同的抽象父类,用户不必关心创建的是哪个子类(without specifying the exact class of object that will be created)
如图所示,用户只需要与工厂交互,类完全被隐藏起来。
这么做的好处是什么?
工厂类包含了必要的逻辑判断,决定创建的对象,用户完全无需了解实现细节,有利于代码的架构优化。
举个例子,去餐厅吃饭,顾客只需要拿到菜单,点菜,餐厅做菜,菜被吃掉。顾客不能也不应该知道这道菜需要哪些原材料,以及餐厅内部是怎么做菜的。
那么这里,顾客就是我们的用户,餐厅就是工厂,而具体的菜(红烧鱼,薯条,凉拌番茄等)就是我们的对象。
#include <stdio.h>
enum {
fish,
chips,
tomato,
};
class food {
public:
virtual void eat() = 0;
virtual ~food(){}
};
class cfish : public food {
public:
void eat() {
printf("fishbone can't be eaten!\n");
}
~cfish(){
printf("fish finished\n");
}
};
class cchips : public food {
public:
void eat() {
printf("chips make you fat!\n");
}
~cchips(){
printf("chips finished\n");
}
};
class ctomato : public food {
public:
void eat() {
printf("I like eatting tomato!\n");
}
~ctomato(){
printf("tomato finished\n");
}
};
class restaurant_factory {
public:
food * cook(int type){
switch (type) {
case fish:
return new cfish();
break;
case chips:
return new cchips();
break;
case tomato:
return new ctomato();
break;
default:
return new cfish();
break;
}
}
};
int main(){
{
restaurant_factory r;
food * f;
f = r.cook(fish);
f->eat();
delete f;
f = r.cook(chips);
f->eat();
delete f;
f = r.cook(tomato);
f->eat();
delete f;
}
return 0;
}