#include <iostream>
using namespace std;
class Base
{
public:
virtual void foo()=0;
};
class DerivedA : public Base
{
public:
void foo()
{
cout << "foo of DerivedA" << endl;
}
};
class DerivedB : public Base
{
public:
void foo()
{
cout << "foo of DerivedB" << endl;
}
};
enum DerivedType
{
DTA, DTB,
};
Base* Create(DerivedType type)
{
switch (type)
{
case DTA:
return new DerivedA();
case DTB:
return new DerivedB();
default:
break;
}
return NULL;
}
template<class T>
Base* CreateByTpl()
{
return new T();
}
int main()
{
Base* pa = Create(DTA);
pa->foo();
Base* pb = Create(DTB);
pb->foo();
pa = CreateByTpl<DerivedA>();
pa->foo();
pb = CreateByTpl<DerivedB>();
pb->foo();
return 0;
}
C++实现工厂模式的例子
最新推荐文章于 2025-05-27 22:08:50 发布