簡(jiǎn)介
????????所謂原型模式就是用原型實(shí)例指定創(chuàng)建對(duì)象的種類碱屁,并且通過復(fù)制這些原型創(chuàng)建新的對(duì)象忽媒。舉一個(gè)簡(jiǎn)單的例子腋粥,一個(gè)人想要批量分發(fā)自己的名片,然而名片千篇一律隘冲,只是偶爾修改一些地方,但需求量大奥邮,所以需要不斷實(shí)例化名片類罗珍,十分麻煩,所以這就有了原型模式蘸朋。原型模式旨在以某一類為原型扣唱,利用Clone成員函數(shù)不斷拷貝出新對(duì)象。
????????在C++中噪沙,有淺拷貝和深拷貝兩種拷貝模式,默認(rèn)賦值采用淺拷貝的方法辐马,但淺拷貝會(huì)共享分配的堆椌忠澹空間,析構(gòu)時(shí)會(huì)兩次釋放空間導(dǎo)致程序崩潰贞奋,所以原型模式一般直接使用深拷貝穷绵,由拷貝構(gòu)造函數(shù)實(shí)現(xiàn)。
????????下面我們就以印名片為例子為大家講解一下原型模式的用法。
圖示
代碼實(shí)現(xiàn)
////////////////////////////
//
// FileName : ProtoTypeDefine.h
// Editor : PeterZheng
// Date : 2018/8/16 18:00
//
////////////////////////////
#pragma once
#ifndef PROTOTYPE_H_
#define PROTOTYPE_H_
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <windows.h>
#endif
#define MAX_LENGTH 255
//克隆抽象類
class ProtoType
{
public:
virtual ProtoType* Clone() = 0;
};
//克隆具體實(shí)現(xiàn)類(名片類)
class ConcreteProtoType
{
public:
int age;
char* name;
char* school;
ConcreteProtoType(int a, const char* name, const char* school)
{
this->age = a;
this->name = new char[MAX_LENGTH];
this->school = new char[MAX_LENGTH];
ZeroMemory(this->name, MAX_LENGTH);
ZeroMemory(this->school, MAX_LENGTH);
strcpy_s(this->name, MAX_LENGTH, name);
strcpy_s(this->school, MAX_LENGTH, school);
}
ConcreteProtoType(const ConcreteProtoType& pt)
{
this->age = pt.age;
this->name = new char[MAX_LENGTH];
this->school = new char[MAX_LENGTH];
ZeroMemory(this->name, MAX_LENGTH);
ZeroMemory(this->school, MAX_LENGTH);
strcpy_s(this->name, MAX_LENGTH, pt.name);
strcpy_s(this->school, MAX_LENGTH, pt.school);
}
~ConcreteProtoType() {}
ConcreteProtoType* Clone()
{
return new ConcreteProtoType(*this);
}
void Show()
{
std::cout << "Name: " << this->name << std::endl << "Age: " << this->age << std::endl << "School: " << this->school << std::endl;
}
};
////////////////////////////
//
// FileName : ProtoTypeDemo.cpp
// Editor : PeterZheng
// Date : 2018/8/16 19:22
//
////////////////////////////
#include "ProtoTypeDefine.h"
using namespace std;
int main(void)
{
ConcreteProtoType *mp1 = new ConcreteProtoType(28, "XiaoMin", "CMU");
ConcreteProtoType *mp2 = mp1->Clone();
//名片的學(xué)校需要改為MIT
ConcreteProtoType *mp3 = new ConcreteProtoType(28, "XiaoMin", "MIT");
ConcreteProtoType *mp4 = mp3->Clone();
mp1->Show();
cout << endl;
mp2->Show();
cout << endl;
mp3->Show();
cout << endl;
system("pause");
return 0;
}