在工厂方法模式下,如果一家公司既能生产单核的,又能生产多核的,那么简单工厂模式和工厂方法模式就无法满足要求,这个时候就需要使用抽象工厂模式了。

#include<iostream>
#include<string>
using namespace std;
enum CTYPE{COREA,COREB};

//定义一个基类单核
class SingleCore 
{
public:
	virtual void show() = 0;
};
//单核A
class SingleCoreA:public SingleCore
{
public:
	void show() {
		cout << "SingleCore A" << endl;
	}
};
//单核B
class SingleCoreB:public SingleCore
{
public:
	void show() {
		cout << "SingleCore B" << endl;
	}
};
//多核
class MultiCore {
public:
	virtual void show() = 0;
};
//多核A
class MultiCoreA :public MultiCore
{
public:
	void show() {
		cout << "MultiCore A" << endl;
	}
};
//多核B
class MultiCoreB :public MultiCore
{
public:
	void show() {
		cout << "MultiCore B" << endl;
	}
};

//工厂
class CoreFactory {
public:
	virtual SingleCore* CreateSingleCore() = 0;
	virtual MultiCore* CreateMultiCore() = 0;
};
//工厂A:专门用来生产A型号的处理器
class FactoryA :public CoreFactory {
public:
	SingleCore* CreateSingleCore() {
		return new SingleCoreA();
	}
	MultiCore* CreateMultiCore() {
		return new MultiCoreA();
	}

};
//工厂B,专门用来生产B型号的处理器
class FactoryB :public CoreFactory {
public:
	SingleCore* CreateSingleCore() {
		return new SingleCoreB();
	}
	MultiCore* CreateMultiCore() {
		return new MultiCoreB();
	}

};
int main() 
{
	FactoryA* a=new FactoryA();
	a->CreateSingleCore()->show();

	getchar();
	return 0;
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐