看COM的时候随手写了一行代码,写完发现是工厂方法模式。。。
废话不多说了
#include "stdafx.h"
#include <iostream>
using namespace std;
class InterfaceA
{
public:
InterfaceA();
virtual ~InterfaceA();
virtual void Func1() = 0;
virtual void Func2() = 0;
};
InterfaceA::InterfaceA(){}
InterfaceA::~InterfaceA(){}
class ComponetB : public InterfaceA
{
public:
ComponetB();
virtual ~ComponetB();
virtual void Func1();
virtual void Func2();
};
ComponetB::ComponetB(){cout<<"组件B创建"<<endl;}
ComponetB::~ComponetB(){cout<<"组件B析构"<<endl;}
void ComponetB::Func1(){cout<<"CompoentB::Func1 is called
";}
void ComponetB::Func2(){cout<<"ComponetB::Func2 is called
";}
class ComponetC : public InterfaceA
{
public:
ComponetC();
virtual ~ComponetC();
virtual void Func1();
virtual void Func2();
};
ComponetC::ComponetC(){cout<<"组件C创建"<<endl;}
ComponetC::~ComponetC(){cout<<"组件C析构"<<endl;}
void ComponetC::Func1(){cout<<"ComponentC::Fucn1 is called
";}
void ComponetC::Func2(){cout<<"ComponetC::Func2 is called
";}
class IFactory
{
public:
IFactory();
virtual ~IFactory();
virtual InterfaceA* CreateInstance() = 0;
protected:
InterfaceA* m_ptrIA;
};
IFactory::IFactory() : m_ptrIA(NULL){}
IFactory::~IFactory(){if(NULL != m_ptrIA) delete m_ptrIA; m_ptrIA = NULL;}
class FactoryB : public IFactory
{
public:
FactoryB();
virtual ~FactoryB();
virtual InterfaceA* CreateInstance();
};
FactoryB::FactoryB() : IFactory(){}
FactoryB::~FactoryB(){if(NULL != m_ptrIA) delete m_ptrIA; m_ptrIA = NULL;}
InterfaceA* FactoryB::CreateInstance(){return (m_ptrIA = new ComponetB());}
class FactoryC : public IFactory
{
public:
FactoryC();
virtual ~FactoryC();
virtual InterfaceA* CreateInstance();
};
FactoryC::FactoryC() : IFactory(){}
FactoryC::~FactoryC() {if(NULL != m_ptrIA) delete m_ptrIA; m_ptrIA = NULL;}
InterfaceA* FactoryC::CreateInstance(){return (m_ptrIA = new ComponetC());}
int _tmain(int argc, _TCHAR* argv[])
{
IFactory* pFactory = new FactoryB();
InterfaceA* pInterface = pFactory->CreateInstance();
pInterface->Func1();
cout<<endl;
pInterface->Func2();
cout<<endl<<endl;
delete pFactory;
pFactory = new FactoryC();
pInterface = pFactory->CreateInstance();
pInterface->Func1();
cout<<endl;
pInterface->Func2();
delete pFactory;
return 0;
}