1 原型模式
原型模式其实就是从一个对象再创建另外一个可定制对象,而且不需要知道任何创建的细节。
假设有一个简历,需要针对不同的公司修改其中的投递意向,在创建简历的时候,其他信息都不变,就一个内容不一样,如果针对不同的简历创建不同的实例,则每次创建简历都需要对其中的初始化参数进行赋值,并不是一个比较优质的解决方案。此时可以采用原型模式。
2 代码实现
//CommunicateStruct.h
#pragma once
#include <string>
using namespace std;
class CommunicateStruct
{
public:
CommunicateStruct(int ,int );
~CommunicateStruct(void);
void setCompany(string);
int m_id;
int m_age;
string m_company;
};
//CommunicateStruct.cpp
#include "StdAfx.h"
#include "CommunicateStruct.h"
CommunicateStruct::CommunicateStruct(int id,int age)
{
m_id = id;
m_age = age;
}
void CommunicateStruct::setCompany(string name)
{
m_company = name;
}
CommunicateStruct::~CommunicateStruct(void)
{
}
在我们的main函数中,实现三份简历的方法:
// Prototype.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "CommunicateStruct.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
CommunicateStruct p(0,18);
p.setCompany("a");
CommunicateStruct t = p;
t.setCompany("b");
CommunicateStruct y = p;
y.setCompany("c");
cout<<p.m_id<<" "<<p.m_age<<" "<<p.m_company<<endl;
cout<<t.m_id<<" "<<t.m_age<<" "<<t.m_company<<endl;
cout<<y.m_id<<" "<<y.m_age<<" "<<y.m_company<<endl;
int instring;
cin>>instring;
return 0;
}
可以看到,该方法可以实现快速创建3分简历,而且只是修改一下公司的名字即可。
3 用指针,不直接使用对象
事实上,我们c++上通常会遇到一些情况,导致我们需要用指针定义对象:
(1)传参的需要
(2)多态的需求
(3)前向声明,不需要立即创建对象,解耦的需要
如果直接把上面改成指针:
CommunicateStruct *p = new CommunicateStruct(0,18);
p->setCompany("a");
CommunicateStruct *t = p;
t->setCompany("b");
CommunicateStruct *y = p;
y->setCompany("c");
cout<<p->m_id<<" "<<p->m_age<<" "<<p->m_company<<endl;
cout<<t->m_id<<" "<<t->m_age<<" "<<t->m_company<<endl;
cout<<y->m_id<<" "<<y->m_age<<" "<<y->m_company<<endl;
这样很明显是错的,此时需要创建一个Clone函数。
CommunicateStruct *CommunicateStruct::Clone()
{
return new CommunicateStruct(m_id,m_age);
}
而使用的时候,Clone一下即可。
CommunicateStruct *p = new CommunicateStruct(0,18);
p->setCompany("a");
CommunicateStruct *t = p->Clone();
t->setCompany("b");
CommunicateStruct *y = p->Clone();
y->setCompany("c");