欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式-抽象模式

程序员文章站 2024-01-20 17:38:34
...

抽象工厂模式相较于工厂模式可以进行一系列接口的实现;但使用的接口被固定,无法在不修改原来的代码的情况下增加接口;

代码实现:

#include<iostream>

using namespace std;
class Fruit
{
public:
	virtual void GetFruit() = 0;
};
class NorthApple:public Fruit
{
public:
	virtual void GetFruit()
	{
		cout << "i am NorthApple" << endl;
	}
};

class NorthBanana :public Fruit
{
public:
	virtual void GetFruit()
	{
		cout << "i am NorthBanana" << endl;
	}
};

class SouthApple :public Fruit
{
public:
	virtual void GetFruit()
	{
		cout << "i am SouthApple" << endl;
	}
};

class SouthBanana :public Fruit
{
public:
	virtual void GetFruit()
	{
		cout << "i am SothBanana" << endl;
	}
};


class AbFactory
{
public:
	virtual Fruit* SetApple() = 0;
	virtual Fruit* SetBanana() = 0;
};

class NorthFactory:public AbFactory
{
public:
	virtual Fruit* SetApple()
	{
		return new NorthApple;
	}
	virtual Fruit* SetBanana()
	{
		return new NorthBanana;
	}
};

class SouthhFactory :public AbFactory
{
public:
	virtual Fruit* SetApple()
	{
		return new SouthApple;
	}
	virtual Fruit* SetBanana()
	{
		return new SouthBanana;
	}
};

int main()
{
	AbFactory* Abf = nullptr;
	Fruit* f = nullptr;


	Abf = new NorthFactory;
	f = Abf->SetApple();
	f->GetFruit();
	delete f;

	f = Abf->SetBanana();
	f->GetFruit();
	delete f;
	delete Abf;


	return system("pause");
}
相关标签: 抽象工厂