#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
using namespace std;
class Fruit {
public:
virtual void getFruit() = 0;
};
class AbFactory {
public:
virtual Fruit* CreateAppleProduct() = 0;
virtual Fruit* CreateBannerProduct() = 0;
};
class NorthApple : public Fruit {
public:
void getFruit()
{
cout << "我是北方的苹果" << endl;
}
};
class SouthApple : public Fruit {
public:
void getFruit()
{
cout << "我是南方的苹果" << endl;
}
};
class NorthBannar : public Fruit {
public:
void getFruit()
{
cout << "我是北方的香蕉" << endl;
}
};
class SouthBannar : public Fruit {
public:
void getFruit()
{
cout << "我是南方的香蕉" << endl;
}
};
class NorthFactory : public AbFactory {
public:
Fruit* CreateAppleProduct()
{
return new NorthApple();
}
Fruit* CreateBannerProduct()
{
return new NorthBannar();
}
};
class SouthFactory : public AbFactory {
public:
Fruit* CreateAppleProduct()
{
return new SouthApple();
}
Fruit* CreateBannerProduct()
{
return new SouthBannar();
}
};
int main(void)
{
AbFactory *aft = new NorthFactory();
AbFactory *aft1 = new SouthFactory();
Fruit * ft = aft->CreateAppleProduct();
Fruit * ft1 = aft->CreateBannerProduct();
ft->getFruit();
ft1->getFruit();
Fruit * ft2 = aft1->CreateAppleProduct();
Fruit * ft3 = aft1->CreateBannerProduct();
ft2->getFruit();
ft3->getFruit();
system("pause");
return EXIT_SUCCESS;
}
c++设计模式之抽象工厂模式
本文通过一个实例展示了如何使用工厂模式和抽象工厂模式来创建不同地区的水果对象。代码中定义了抽象类Fruit和AbFactory,以及它们的具体实现如NorthApple、SouthApple、NorthBannar和SouthBannar。在main函数中,通过不同的工厂对象创建并打印出不同地区的苹果和香蕉,体现了工厂模式在对象创建时的灵活性。
摘要由CSDN通过智能技术生成