首页 > 代码库 > 随手写了几行代码
随手写了几行代码
看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 \n";}void ComponetB::Func2(){cout<<"ComponetB::Func2 is called \n";} 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 \n";}void ComponetC::Func2(){cout<<"ComponetC::Func2 is called \n";}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;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。