C++工厂方法模式
#include <iostream>
using namespace std;
class Plant //工厂
{
public:
virtual void ShowName() = 0;
};
class Lamborghini :public Plant //兰博基尼工厂
{
public:
void ShowName() {
cout << "兰博基尼工厂生产的超跑" << endl;
}
};
class Ferrari :public Plant //法拉利工厂
{
public:
void ShowName() {
cout << "法拉利工厂生产的超跑" << endl;
}
};
class Bugatti :public Plant //布加迪工厂
{
public:
void ShowName() {
cout << "布加迪工厂生产的超跑" << endl;
}
};
class SynthesizePlant {
public:
virtual Plant*CreatePlant() = 0;
};
class LamborghiniPlant :public SynthesizePlant
{
public:
Plant* CreatePlant() {
return new Lamborghini;
}
};
class FerrariPlant :public SynthesizePlant
{
public:
Plant* CreatePlant() {
return new Ferrari;
}
};
class BugattiPlant :public SynthesizePlant
{
public:
Plant* CreatePlant() {
return new Bugatti;
}
};
void test() {
SynthesizePlant*Splant =NULL;
Plant*myPlant = NULL;
Splant = new LamborghiniPlant;
myPlant = Splant->CreatePlant();
myPlant->ShowName();
delete Splant;
delete myPlant;
Splant = new FerrariPlant;
myPlant = Splant->CreatePlant();
myPlant->ShowName();
delete Splant;
delete myPlant;
Splant = new BugattiPlant;
myPlant = Splant->CreatePlant();
myPlant->ShowName();
delete Splant;
delete myPlant;
}
void main() {
test();
}
效果图: