//符合开闭性原则,标准的设计模式,面向接口编程,利用工厂类产生各种类型,扩展性强
#include <iostream>
using namespace std;
class Fruit
{
public:
virtual void getFruit() = 0;
protected:
private:
};
class Banana : public Fruit //实现关系
{
public:
virtual void getFruit()
{
cout << "我是香蕉...." << endl;
}
protected:
private:
};
class Apple : public Fruit //实现关系
{
public:
virtual void getFruit()
{
cout << "我是苹果...." << endl;
}
protected:
private:
};
class Factory
{
public:
virtual Fruit *create() = 0;
};
class Banana_fac :public Factory
{
virtual Fruit *create()
{
return new Banana;
}
};
class Apple_fac :public Factory
{
virtual Fruit *create()
{
return new Apple;
}
};
void main()
{
Factory *f = NULL;
Fruit *fruit = NULL;
//工厂生产 香蕉
f = new Banana_fac; //父类指针指向子类对象,类型兼容性原则
fruit = f->create(); //继承 虚函数重写 父类指针指向子类对象
fruit->getFruit();
delete fruit;
delete f;
f = new Apple_fac;
fruit = f->create();
fruit->getFruit();
delete fruit;
delete f;
cout << "hello..." << endl;
system("pause");
return;
}
工厂模式
最新推荐文章于 2024-08-25 10:48:58 发布