단순factory

7703 단어 factory
매개 변수 화학 공장 모델은 두 가지 문제를 해결할 수 있다.개체 작성을 패키지화합니다. 2.객체 작성 지연
// 
class TypeBase
{
public:
    TypeBase();
    virtual ~TypeBase();
    virtual void Speak() = 0;
};

TypeBase::TypeBase()
{
}
TypeBase::~TypeBase()
{

}
// 
#include"typebase.h"
class IntType:public TypeBase
{
public:
    IntType();
    ~IntType();
    void Speak();
private:
    int m_Buf;
};
#include "inttype.h"
#include<QDebug>
IntType::IntType()
{
    m_Buf = 5000;
}

IntType::~IntType()
{

}

void IntType::Speak()
{
    qDebug()<<m_Buf;
}

#include"typebase.h"
#include<QString>
class StrType:public TypeBase
{
public:
    StrType();
    ~StrType();
    void Speak();
private:
    QString m_Buf;
};
#include "strtype.h"
#include<QDebug>
StrType::StrType()
{
    m_Buf = "Hello,I am Type QString";
}
StrType::~StrType()
{

}
void StrType::Speak()
{
    qDebug()<<m_Buf;
}
//
#include"typebase.h"
#include"strtype.h"
#include"inttype.h"
class TypeFactory
{
protected:
    TypeFactory();
public:
    static TypeFactory* GetInstance();
    TypeBase *CreateType(QString typeName);
private:
  static TypeFactory* m_Instance;
};
#include "typefactory.h"
TypeFactory* TypeFactory::m_Instance = 0;
TypeFactory::TypeFactory()
{
}

TypeFactory* TypeFactory::GetInstance()
{
    if(0 == m_Instance)
        m_Instance = new TypeFactory();
    return m_Instance;
}

TypeBase* TypeFactory::CreateType(QString typeName)
{
    if("INT" == typeName)
        return new IntType();
    else if("STRING" == typeName)
        return new StrType();
    else
        return 0;
}
//
 TypeFactory *factory = TypeFactory::GetInstance();
    TypeBase * type = factory->CreateType("INT");
    type->Speak();
    TypeBase * type2 = factory->CreateType("STRING");
    type2->Speak();

좋은 웹페이지 즐겨찾기