c++设计模式之抽象工厂模式

本文通过一个实例展示了如何使用工厂模式和抽象工厂模式来创建不同地区的水果对象。代码中定义了抽象类Fruit和AbFactory,以及它们的具体实现如NorthApple、SouthApple、NorthBannar和SouthBannar。在main函数中,通过不同的工厂对象创建并打印出不同地区的苹果和香蕉,体现了工厂模式在对象创建时的灵活性。
摘要由CSDN通过智能技术生成
#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值