#include "stdafx.h"
#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;
}
C ++ 抽象工厂模型
最新推荐文章于 2024-08-05 14:57:08 发布