原型模式
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
示例:
prototype.h
#pragma once
#include "windows.h"
#include "stdio.h"
#pragma warning(disable:4996)
class ProtoType
{
public:
virtual ProtoType * clone() = 0;
public:
char * pchar;
};
class ConcreteProtoType :public ProtoType
{
public:
ConcreteProtoType()
{
pchar = new char[100];
Sleep(1000);// 模拟构造函数的复杂性,构造比较麻烦,拷贝构造可以快速复制一份出来
strcpy(pchar, "Hello world");
printf("ConcreteProtoType::ConcreteProtoType()\n");
}
~ConcreteProtoType()
{
if (pchar != nullptr)
{
delete pchar;
pchar = nullptr;
}
}
ConcreteProtoType(const ConcreteProtoType& other)// 深copy
{
pchar = new char[100];
strcpy(pchar, other.pchar);
printf("ConcreteProtoType::ConcreteProtoType(const ConcreteProtoType& other)\n");
}
ProtoType* clone()
{
ConcreteProtoType* prototype = new ConcreteProtoType(*this);// 将自己复制一份,深copy,没有耗时的sleep
return prototype;
}
};
main.cpp
#include "prototype.h"
#include <stdio.h>
void main()
{
ProtoType* p1 = new ConcreteProtoType();
ProtoType* p2 = p1->clone();
printf("p1:%s,p2:%s\n", p1->pchar, p2->pchar);
getchar();
}
运行结果:
ConcreteProtoType::ConcreteProtoType()
ConcreteProtoType::ConcreteProtoType(const ConcreteProtoType& other)
p1:Hello world,p2:Hello world