简单工厂
简单工厂不属于一种设计模式,实际应用于较小的项目中。
它包含如下角色:
1.Factory 工厂角色
2.Product 抽象产品
3.ConcreteProduct 具体产品角色
实例:麦当劳,可以选择芝士汉堡、鸡翅等食品。作为消费者(Client),你不需要考虑这些食品(对象)如何生产(对象创建)的,只需要提出你的选择,然后由麦当劳店(这个工厂来创建)去生产对应的产品。
#include <iostream>
#include <string>
using namespace std;
/// (Abstract) Product //
// Macdonal's abstract food
class McFood
{
public:
virtual void getFood() = 0;
};
/// Concrete Product //
// Macdonal's concrete food
class CheesBurger : public McFood
{
public:
// override
void getFood()
{
cout << "Here is your cheesburger, enjoy it!" << endl;
}
};
class McWings : public McFood
{
public:
// override
void getFood()
{
cout << "Here is your McWings, enjoy it!" << endl;
}
};
// if someone want the frechfries, you can do it by yourself !
class FrenchFries
{
};
/// Factory //
class McFoodFactory
{
public:
static McFood* produceMcFood(string foodname)
{
{
if (foodname == "cheesburger")
{
return new CheesBurger;
}
else if (foodname == "mcwings")
{
return new McWings;
}
else
{
return nullptr;
}
}
}
};
Client
int main()
{
// abstract class
McFood* mcfood = nullptr;
// customer wanna some concrete food, here changed by customer.
string customwant = "cheesburge";
// invock the Factory to produce the food which the customer want
try
{
mcfood = McFoodFactory::produceMcFood(customwant);
// get the food
if (!mcfood)
throw "Sorry, the product isn't on the menu";
else
mcfood->getFood();
}
catch (const char* e)
{
cout << e << endl;
}
delete mcfood;
return 0;
}
思考与动手:
1、绘制上述代码的类图;
2、为什么它不属于设计模式的一种?
3、若要增加一个产品,绘制出类图,并加以实现;
4、这里涉及到抽象类的指针,为什么不直接用对象?
5、做个小程序实现异常处理功能。
1.类图
2.
不属于设计模式,因为它违反了高类聚责任分配原则,为所有的实例创建逻辑,将全部的逻辑集中在一个工厂类中,它所创建的类只能是事先考虑的,如果需要添加新的类,则需要改变工厂类,对系统的维护特别不利。
3.
实现如下:
//新建的FrenchFries类
class FrenchFries: public McFood
{
public:
// override
void getFood()
{
cout << "Here is your FrenchFries, enjoy it!" << endl;
}
};
//工厂类修改如下
class McFoodFactory
{
public:
static McFood* produceMcFood(string foodname)
{
{
if (foodname == "cheesburger")
{
return new CheesBurger;
}
else if (foodname == "mcwings")
{
return new McWings;
}
//以下是修改的内容
else if (foodname == "frechfries")
{
return new FrenchFries;
}
else
{
return nullptr;
}
}
}
};
4.
如果直接用对象,会生成基类的实例并分配内存,但是C++中抽象类是不能被实例化的。而指针就不一样了,它不具备任何信息,不论是指向基类还是派生类,都不会产生任何影响,其本身就只占一个4字节的内存空间而已。
5.
除数为0时的异常
#include<iostream>
using namespace std;
int main() {
int a,b;
double c;
cout << "please cin two number:" << endl;
cin >> a;
cin >> b;
try{
if (b == 0) {
throw "被除数为0!";
}else {
c = (double)a /b;
cout << c << endl;
}
}catch (const char* msg) {
cout << msg << endl;
}
return 0;
}