設計模式之——原型模式

prototype.h

#ifndef PROTOTYPE_H
#define PROTOTYPE_H
#include <QtDebug>

class Prototype
{
public:
    Prototype(){}
    virtual ~Prototype(){}
    virtual Prototype *clone() const = 0; //定義clone接口,根據不同的派生類來實例化對象
    virtual void show() = 0;
};
#endif // PROTOTYPE_H

ConcretePrototypeA.h

#ifndef CONCRETEPROTOTYPEA_H
#define CONCRETEPROTOTYPEA_H
#include <QtDebug>
#include "prototype.h"

class ConcretePrototypeA : public Prototype
{
public:
    ConcretePrototypeA(QString name):m_name(name){}
    ~ConcretePrototypeA(){}

    //拷貝構造函數
    ConcretePrototypeA(const ConcretePrototypeA &other)
    {
        m_name = other.m_name;
    }

    //實現基類定義的Clone接口,內部調用拷貝構造函數實現複製功能
    ConcretePrototypeA* clone() const
    {
        return new ConcretePrototypeA(*this);
    }

    void show(){ qDebug() << m_name << " 你好";}

//private:
    QString m_name;
};

#endif // CONCRETEPROTOTYPEA_H

main.cpp

#include <QApplication>
#include "prototype.h"
#include "ConcretePrototypeA.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Prototype *p1 = new ConcretePrototypeA("小明");
    Prototype *p2 = p1->clone();
    p1->show();
    p2->show();

    delete p1;
    delete p2;

    return a.exec();
}

原型模式就是從一個對象再創建另外一個可定製的對象,而且不需知道任何創建的細節。
UML
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章