#include <iostream>
using namespace std;
// 水果抽象类
class CAbstractFruit
{
public:
virtual void ShowName() = 0;
};
// 苹果类
class CApple : public CAbstractFruit
{
public:
virtual void ShowName()
{
cout << " 我是苹果!" << endl;
}
};
// 香蕉类
class CBanana : public CAbstractFruit
{
public:
virtual void ShowName()
{
cout << " 我是香蕉!" << endl;
}
};
// 鸭梨类
class CPear : public CAbstractFruit
{
public:
virtual void ShowName()
{
cout << " 我是鸭梨!" << endl;
}
};
// 水果工厂类
class CFruitFactory
{
public:
static CAbstractFruit* CreateFruit(string flag)
{
if (flag == "apple")
{
return new CApple;
}
else if (flag == "banana")
{
return new CBanana;
}
else if (flag == "pear")
{
return new CPear;
}
else
{
return nullptr;
}
}
};
int main()
{
CAbstractFruit* fruit = CFruitFactory::CreateFruit("apple");
if (fruit != nullptr)
{
fruit->ShowName();
}
delete fruit;
fruit = CFruitFactory::CreateFruit("banana");
if (fruit != nullptr)
{
fruit->ShowName();
}
delete fruit;
fruit = CFruitFactory::CreateFruit("pear");
if (fruit != nullptr)
{
fruit->ShowName();
}
delete fruit;
cin.get();
return 0;
}