工厂可以由不同的需求生产不同的产品,例如矿场 ,可以加个铁矿,铜矿,金矿等等,文化用品制造厂可以制造铅笔,钢笔,中性笔等等。
选择场景:我们在画图板画图或者写字的时候选择不同的画笔类型可以画出不同效果的图像,假如现在要求我们实现一个画笔工厂,可以写不同的类型的字。
UML类图如下
代码如下
class Pen
{
public:
Pen(){}
virtual ~Pen(){}
virtual void drawText(std::string str) = 0;
};
class DotPen :public Pen
{
public:
DotPen(){}
virtual ~DotPen(){}
virtual void drawText(std::string str)
{
cout << "DotPen::" << str << endl;
}
};
class SolidPen :public Pen
{
public:
SolidPen(){}
virtual ~SolidPen(){}
virtual void drawText(std::string str)
{
cout << "SolidPen::" << str << endl;
}
};
class SawtoothPen :public Pen
{
public:
SawtoothPen(){}
virtual ~SawtoothPen(){}
virtual void drawText(std::string str)
{
cout << "SawtoothPen::" << str << endl;
}
};
class PenFactory
{
public:
enum PenType
{
Solid,
Dot,
Sawtooth
};
static Pen* CreatePen(PenType type)
{
switch (type)
{
case PenFactory::Solid:
return new SolidPen;
case PenFactory::Dot:
return new DotPen;
case PenFactory::Sawtooth:
return new SawtoothPen;
}
return nullptr;
}
static void DestoryPen(Pen* pen)
{
if(pen)
{
delete pen;
pen = nullptr;
}
}
};
测试
int main()
{
Pen* pdot=PenFactory::CreatePen(PenFactory::Dot);
pdot->drawText("hello");
PenFactory::DestoryPen(pdot);
Pen* psolid = PenFactory::CreatePen(PenFactory::Solid);
psolid->drawText("hello");
PenFactory::DestoryPen(psolid);
getchar();
return 0;
}