#include <iostream>
using namespace std;
template <typename Base, typename Derive>
class Factory
{
public:
Factory():m_pointer(NULL){}
Base *create()
{
if (m_pointer != NULL)
return m_pointer;
m_pointer = new Derive();
return m_pointer;
}
void free()
{
if (m_pointer != NULL)
delete m_pointer;
m_pointer = NULL;
}
~Factory(){free();}
private:
Base *m_pointer;
};
class Product
{
public:
virtual ~Product(){}
virtual void show() =0;
};
class Product1 : public Product
{
void show()
{
cout<<"Product1"<<endl;
}
};
class Product2 : public Product
{
void show()
{
cout<<"Product2"<<endl;
}
};
typedef Factory<Product, Product1> Factory1;
typedef Factory<Product, Product2> Factory2;
int main()
{
Factory1 facory1;
Factory2 facory2;
facory1.create()->show();
facory2.create()->show();
return 0;
}
factorymethod 工厂方法模式
最新推荐文章于 2024-12-04 09:53:19 发布