#include <iostream>
using namespace std;
class BreadMaker
{
public:
virtual void GetBread()
{
// NOTING
}
};
// 黑面包代码
class BlackBread : public BreadMaker
{
public:
void GetBread()
{
cout << "小面烤出了黑面包" << endl;
}
};
// 蜂蜜面包代码
class HoneyBread : public BreadMaker
{
public:
void GetBread()
{
cout << "小面烤出了蜂蜜面包" << endl;
}
}
// 白面包代码
class WhiteBread : public BreadMaker
{
public:
void GetBread()
{
cout << "小面烤出了白面包" << endl;
}
}
// 面包工厂
class BreadFactory
{
public:
static BreadMaker* MakeBread(int breadType)
{
BreadMaker *breadMaker = NULL;
switch(breadType)
{
case 1:
breadMaker = new BlackBread();
break;
case 2:
breadMaker = new HoneyBread();
break;
case 3:
breadMaker = new WhiteBread();
break;
default:
break;
}
return BreadMaker;
}
}
int main()
{
BreadMaker *breadMaker = NULL;
cout << "小面的面包店开业了!" << endl;
cout << "顾客要黑面包" << endl;
breadMaker = BreadFactory::MakeBread(1);
breadMaker->GetBread();
cout << "顾客要蜂蜜面包" << endl;
breadMaker = BreadFactory::MakeBread(2);
breadMaker->GetBread();
cout << "顾客要白面包" << endl;
breadMaker = BreadFactory::MakeBread(3);
breadMaker->GetBread();
return 0;
}
简单工厂模式
最新推荐文章于 2024-08-25 10:50:01 发布