#include<iostream>
using namespace std;
//工厂模式不符合 开闭原则
class AbstractFruit {
public:
virtual void ShowName() = 0;
};
class Banana :public AbstractFruit {
public:
virtual void ShowName() {
cout << "我是香蕉" << endl;
}
};
class Pear :public AbstractFruit {
public:
virtual void ShowName() {
cout << "我是鸭梨" << endl;
}
};
class Apple :public AbstractFruit {
public:
virtual void ShowName() {
cout << "我是苹果" << endl;
}
};
//水果工厂
//class FruitFactory
//{
//public:
// static AbstractFruit* CrateFruit(string flag) {
// if (flag == "apple")
// {
// return new Apple;
// }
// else if (flag == "babana")
// {
// return new Banana;
// }
// else if (flag == "Pear")
// {
// return new Pear;
// }
// else
// {
// return NULL;
// }
// }
//};
class AbstactFruitFactory
{
public :
virtual AbstractFruit* CreateFruit() = 0;
};
//苹果工厂
class AppleFactory :public AbstactFruitFactory
{
public:
virtual AbstractFruit* CreateFruit() {
return new Apple;
}
};
class BabanaFactory :public AbstactFruitFactory
{
public:
virtual AbstractFruit* CreateFruit() {
return new Banana;
}
};
class PearFactory :public AbstactFruitFactory
{
public:
virtual AbstractFruit* CreateFruit() {
return new Pear;
}
};
void test01() {
AbstactFruitFactory* factory = NULL;
AbstractFruit* fruit = NULL;
factory = new AppleFactory;
fruit = factory->CreateFruit();
fruit->ShowName();
delete fruit;
delete factory;
}
int main()
{
test01();
system("pause");
return 0;
}
设计模式-工厂方法
最新推荐文章于 2022-06-02 23:05:53 发布