1. 程式人生 > >設計模式在遊戲中的應用--原型模式(六)

設計模式在遊戲中的應用--原型模式(六)

markdown 什麽 java 原型模型 char mod 結構圖 void -s

Prototype原型模式是一種創建型設計模式,Prototype模式同意一個對象再創建另外一個可定制的對象,根本無需知道不論什麽怎樣創建的細節,工作原理是:通過將一個原型對象傳給那個要發動創建的對象,這個要發動創建的對象通過請求原型對象拷貝它們自己來實施創建。
技術分享

上面是原型模式的UML結構圖。


以下是原型模式的代碼:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class IClone
{
public:
    IClone
(){}; virtual ~IClone(){}; public: virtual IClone* Clone() =0; }; class Player:public IClone { public: Player() { m_name = "test"; m_id = 1; }; IClone* Clone() { Player* ret = new Player(); ret->SetName(m_name); return ret; } void
SetName( string name ) { m_name = name; } string GetName() { return m_name; } void SetId( int id ) { m_id = id; } int GetId() { return m_id; } private: string m_name; int m_id; }; int _tmain(int argc, _TCHAR* argv[]) { Player* player1 = new
Player(); player1->SetId(3); player1->SetName("cloneObject"); Player* player2 = (Player*)player1->Clone(); cout<<player2->GetName()<<endl; cout<<player2->GetId()<<endl; return 0; }

輸出結果例如以下:
技術分享

原型模型屬於一個構建模式。事實上和拷貝構造函數很類似,曾經我一直感覺原型模式全然是個沒用的東西,可是隨著代碼寫多了。發現原型模型不須要全然一樣時候能發揮很不錯的作用,而拷貝構造必須全然拷貝,由於它可能被用於函數參數。

設計模式在遊戲中的應用--原型模式(六)