#include <iostream>
using namespace std;
//简单工厂模式+ 开闭原则 = 工厂方法模式
//定义创建产品的工厂接口,实例化不同的工厂,创建不同的类,被创建的类具有相同的父类。
class Fruit {
public:
virtual void createFruit() = 0;
};
class Factory {
public:
virtual Fruit* create() = 0;
};
class orangeFruit;
class orangeFactory :public Factory {
public:
Fruit* create();
};
class orangeFruit : public Fruit {
public:
void createFruit()
{
cout << "create orange" << endl;
}
};
Fruit* orangeFactory::create() {
return new orangeFruit;
}
class appleFruit : public Fruit {
public:
void createFruit()
{
cout << "create apple" << endl;
}
};
class appleFactory :public Factory {
public:
Fruit* create()
{
return new appleFruit;
}
};
int main02()
{
Fruit* fruit = NULL;
Factory* fatory = NULL;
//橘子工厂
fatory = new orangeFactory;
fruit = fatory->create();
fruit->createFruit();
delete fatory;
delete fruit;
fruit = NULL;
fatory = NULL;
//苹果
fatory = new appleFactory;
fruit = fatory->create();
fruit->createFruit();
delete fatory;
delete fruit;
fruit = NULL;
fatory = NULL;
return 0;
}
工厂方法模式
最新推荐文章于 2024-04-19 14:53:35 发布