AbstractFactory模式
个人觉得这个模式跟工厂模式的关系
就像数和数组,字符和字符串的关系类似
工厂要创建多个类的时候,根据类别区分
AbstractFactory.h
#ifndef _ABSTRACTFACTORY_H
#define _ABSTRACTFACTORY_H
#include <iostream>
using namespace std;
class AbstractProjectA
{
public:
virtual ~AbstractProjectA() {}
protected:
AbstractProjectA() {};
};
class AbstractProjectB
{
public:
virtual ~AbstractProjectB() {}
protected:
AbstractProjectB() {}
};
class ProjectA1 : public AbstractProjectA
{
public:
ProjectA1() {
cout << "ProjectA1" << endl;
}
~ProjectA1() {};
};
class ProjectA2 : public AbstractProjectA
{
public:
ProjectA2() {
cout << "ProjectA2" << endl;
}
~ProjectA2() {};
};
class ProjectB1 : public AbstractProjectB
{
public:
ProjectB1() {
cout << "ProjectB1" << endl;
}
~ProjectB1() {};
};
class ProjectB2 : public AbstractProjectB
{
public:
ProjectB2() {
cout << "ProjectB2" << endl;
}
~ProjectB2() {};
};
class AbstractFactory
{
public:
virtual ~AbstractFactory() {}
virtual AbstractProjectA* CreateProjectA()=0;
virtual AbstractProjectB* CreateProjectB()=0;
protected:
AbstractFactory() {};
};
class Factory1 : public AbstractFactory
{
public:
Factory1() {};
~Factory1() {};
AbstractProjectA* CreateProjectA() {
return new ProjectA1;
}
AbstractProjectB* CreateProjectB() {
return new ProjectB1;
}
};
class Factory2 : public AbstractFactory
{
public:
Factory2() {};
~Factory2() {};
AbstractProjectA* CreateProjectA() {
return new ProjectA2;
}
AbstractProjectB* CreateProjectB() {
return new ProjectB2;
}
};
#endif // _ABSTRACTFACTORY_H
AbstractFactory.cpp
#include "AbstractFactory.h"
int main()
{
AbstractFactory *f1 = new Factory1;
AbstractFactory *f2 = new Factory2;
f1->CreateProjectA();
f1->CreateProjectB();
f2->CreateProjectA();
f2->CreateProjectB();
return 0;
}
编译:make AbstractFactory