与工厂方法模式的区别是工厂子类中会创建出同一类型的不同产品对象。工厂方法模式则工厂子类中只是创建一种具体的产品对象
结构:
产品基类:子类继承的虚函数方法
具体产品子类:实现该产品功能
工厂基类:工厂子类中存在的抽象方法,即子类中创建对象的抽象方法必须在此类中
工厂子类:有多个创建产品的对象的方法,每一个方法负责创建一个具体产品的对象,这些产品都是属于同一类型即同一组件的产品
#include <iostream>
#include <string>
using namespace std;
/////////////产品
class CLinux
{
public:
virtual ~CLinux() {};
//产品使用公共接口
virtual void Start() = 0;
};
class CLinuxMobile : public CLinux
{
public:
CLinuxMobile()
{
cout << "create linux mobile." << endl;
}
virtual ~CLinuxMobile() {};
virtual void Start()
{
cout << "linux mobile start." << endl;
};
};
class CLinuxPC : public CLinux
{
public:
CLinuxPC()
{
cout << "create linux PC." << endl;
}
virtual ~CLinuxPC() {};
virtual void Start()
{
cout << "linux PC start." << endl;
};
};
class CWindows
{
public:
virtual ~CWindows() {};
//产品使用公共接口
virtual void Start() = 0;
};
class CWindowsMobile : public CWindows
{
public:
CWindowsMobile()
{
cout << "create windows mobile." << endl;
}
virtual ~CWindowsMobile() {};
virtual void Start()
{
cout << "windows mobile start." << endl;
};
};
class CWindowsPC : public CWindows
{
public:
CWindowsPC()
{
cout << "create windows PC." << endl;
}
virtual ~CWindowsPC() {};
virtual void Start()
{
cout << "windows PC start." << endl;
};
};
////工厂
class CFactory
{
public:
virtual ~CFactory(){};
//产品族有个产品组件
virtual CLinux* CreateLinux() = 0;
virtual CWindows* CreateWindows() = 0;
};
class CMobileFactory : public CFactory
{
public:
CMobileFactory()
{
cout << "create mobile factory." << endl;
}
virtual ~CMobileFactory(){};
virtual CLinux* CreateLinux()
{
return new CLinuxMobile;
};
virtual CWindows* CreateWindows()
{
return new CWindowsMobile;
};
};
class CPCFactory : public CFactory
{
public:
CPCFactory()
{
cout << "create PC factory." << endl;
}
virtual ~CPCFactory(){};
virtual CLinux* CreateLinux()
{
return new CLinuxPC;
};
virtual CWindows* CreateWindows()
{
return new CWindowsPC;
};
};
void Test(CFactory* pFactory)
{
CLinux* pLinux = NULL;
CWindows* pWindows = NULL;
pLinux = pFactory->CreateLinux();
pWindows = pFactory->CreateWindows();
pLinux->Start();
pWindows->Start();
delete pWindows;
delete pLinux;
};
int main()
{
CFactory* pFactory = NULL;
//手机工厂。生产手机产品族,种类有Linux和Windows
pFactory = new CMobileFactory;
Test(pFactory);
delete pFactory;
cout << endl;
//PC工厂。生产PC产品族,种类有Linux和Windows
pFactory= new CPCFactory;
Test(pFactory);
delete pFactory;
system("pause");
return 0;
}