VC++简单工厂模式

    技术2022-05-13  0

    //接口类interface IMyInterface{public:   int m_value;  virtual  void  Run()=0;};

    //实现类1class ImplClass1 : public IMyInterface{  //注意这里,必须要public类型继承,否则会出错!!!public:      void Run(){  m_value=100;    _tprintf(_T("ImplClass1 m_value:%d/n"),m_value); }};

    //实现类2class ImplClass2 : public IMyInterface{public:      void Run(){  m_value=200;  _tprintf(_T("ImplClass2 m_value:%d/n"),m_value); }};

    //工厂类class Factory{public:static IMyInterface* Create_ImplClass_Instace(int type){        IMyInterface *result;  switch (type)        {  case 0:             ImplClass1* pImp1;   pImp1=new ImplClass1;   result= dynamic_cast<IMyInterface*>(pImp1);            break;  case 1:             ImplClass2* pImp2;   pImp2=new ImplClass2;   result= dynamic_cast<IMyInterface*>(pImp2);            break;  }    return result; };};

    int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]){   IMyInterface* pImi=NULL; pImi=Factory::Create_ImplClass_Instace(0); pImi->Run(); delete pImi; pImi=Factory::Create_ImplClass_Instace(1); pImi->Run(); delete pImi;}


    最新回复(0)