天天看點

Qt C++ prototype(原型模式或者克隆模式)

prototype.h

#pragma once

#include <QDebug>

#include <QObject>

#include <QString>

class CProtoTypeBase

{

public:

virtual CProtoTypeBase* clone() = 0;

virtual void printAuthor() = 0;

virtual void printGroup() = 0;

void setAuthor(const QString &author){m_author = author;}

QString getAtuthor() const{return m_author;}

private:

QString m_author;

};

class CComputerBook : public CProtoTypeBase

{

public:

CComputerBook(){};

CProtoTypeBase* clone();

void printAuthor();

void printGroup();

};

class CStoryBook : public CProtoTypeBase

{

public:

CStoryBook(){};

CProtoTypeBase* clone();

void printAuthor();

void printGroup();

};

prototype.cpp

#include "prototype.h"

CProtoTypeBase* CComputerBook::clone()

{

CComputerBook *p = new CComputerBook;

*p = *this;

return p;

}

void CComputerBook::printAuthor()

{

qDebug() << "computerAuthor";

}

void CComputerBook::printGroup()

{

qDebug() << "";

}

CProtoTypeBase* CStoryBook::clone()

{

CStoryBook *p = new CStoryBook;

*p = *this;

return p;

}

void CStoryBook::printAuthor()

{

qDebug() << "storyAuthor";

}

void CStoryBook::printGroup()

{

qDebug() << "";

}

main.cpp

#include <QApplication>

#include "prototype.h"

int main(int argc,char **argv)

{

QApplication app(argc,argv);

CProtoTypeBase *computer = new CComputerBook;

computer->setAuthor("xiaojiji");

CProtoTypeBase * com2 = computer->clone();

qDebug() << com2->getAtuthor();

com2->setAuthor("xiaoniuniu");

qDebug() << com2->getAtuthor();

delete computer;

delete com2;

return app.exec();

}

繼續閱讀