现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

Prototype模式C++实现

2012-08-21 05:51 工业·编程 ⁄ 共 1256字 ⁄ 字号 暂无评论

原型模型,画图软件,拖拽图形的例子做比很贴切。

图形类Graph.h:

#pragma once
#include <iostream>
using namespace std;

class CGraph
{
public:
    CGraph()
        : m_strColor(_T("Red"))
    {

    }

    virtual ~CGraph(){}

    virtual CGraph* Clone() = 0;

    virtual void Desc() = 0;

    void SetColor(const CString& strColor)
    {
        m_strColor = strColor;
    }

protected:
    CString m_strColor;
};

//圆
class CCircle : public CGraph
{
public:
    CGraph* Clone()
    {
        CCircle* pCircle = new CCircle();
        *pCircle = *this;

        return pCircle;
    }

    virtual void Desc()
    {
        cout<<_T("Circle ")<<m_strColor<<endl;
    }
};

//方
class CSquare : public CGraph
{
public:
    CGraph* Clone()
    {
        CSquare* pCircle = new CSquare();
        *pCircle = *this;

        return pCircle;
    }

    virtual void Desc()
    {
        cout<<_T("Square ")<<m_strColor<<endl;
    }
};

调用方法:

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    //圆形
    CGraph* pCircle1 = new CCircle();
    CGraph* pCircle2 = pCircle1->Clone();
    pCircle1->SetColor(_T("Blue"));

    pCircle1->Desc();
    pCircle2->Desc();

    delete pCircle1;
    pCircle1 = NULL;
    delete pCircle2;
    pCircle2 = NULL;

    //方形
    CGraph* pSquare1 = new CSquare();
    CGraph* pSquare2 = pSquare1->Clone();
    pSquare1->SetColor(_T("Black"));

    pSquare1->Desc();
    pSquare2->Desc();

    delete pSquare1;
    pSquare1 = NULL;
    delete pSquare2;
    pSquare2 = NULL;

    return 0;
}

给我留言

留言无头像?