首页 > 其他 > 详细

随手写了几行代码

时间:2014-07-19 08:28:22      阅读:284      评论:0      收藏:0      [点我收藏+]

 

看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;
}

随手写了几行代码,布布扣,bubuko.com

随手写了几行代码

原文:http://www.cnblogs.com/cuish/p/3854448.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!