设计模式----原形模式
发表时间:2020-10-18
发布人:葵宇科技
浏览次数:38
原形模式类似于拷贝构造函数,提供一种可以直接拷贝原对象的方法,这种方法比较简单,就不画类图了,直接看一下对应代码:
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
virtual Person *Clone() = 0;
virtual void Print() = 0;
};
class CppProgramer : public Person {
public:
CppProgramer() : m_Name(""), m_Age(0), m_pAddress(NULL) {}
CppProgramer(string name, int age, const char *pszAddr) : m_Name(name), m_Age(age), m_pAddress(new char[strlen(pszAddr)]) {
}
void Print() {
cout << "C++程序员的姓名: " << m_Name << "年龄: " << m_Age << endl;
}
Person *Clone() {
CppProgramer* tmp = new CppProgramer;
tmp->m_Name = this->m_Name;
tmp->m_Age = this->m_Age;
int iLen = strlen(m_pAddress) + 1;
tmp->m_pAddress = new char[iLen];
strcpy(tmp->m_pAddress, this->m_pAddress);
return(tmp);
}
~CppProgramer() {
if (m_pAddress) {
delete[] m_pAddress;
m_pAddress = NULL;
}
}
private:
string m_Name;
char* m_pAddress;
int m_Age;
};
int main() {
const char* pszAddr = "中山路";
CppProgramer cpp("YangMing", 15, pszAddr);
Person* p = cpp.Clone();
p->Print();
system("pause");
return(0);
}
(完)