原型模式
用原型实例指定创建对象的种类, 并且通过拷贝这些原型创建新的对象。(细节需自己处理)
// 抽象原型
class prototype
{
public:
prototype() {}
virtual ~prototype() {}
public:
virtual prototype* clone() = 0;
virtual void freeClone() = 0;
};
// 具体实现
class concretePrototype : public prototype
{
public:
concretePrototype() {
name = (char*)malloc(20);
if (name != NULL) {
sprintf(name, "%s", "hello world!");
}
}
~concretePrototype() {
if (name != NULL) {
free(name);
name = NULL;
}
}
public:
virtual prototype* clone() {
concretePrototype* proto = (concretePrototype*)malloc(sizeof(concretePrototype));
if (proto != NULL) {
memcpy(proto, this, sizeof(concretePrototype));
proto -> name = (char*)malloc(20);
if (proto != NULL) {
memcpy(proto->name, this->name, 20);
}
}
return proto;
}
virtual void freeClone() {
if (name != NULL) {
free(name);
name = NULL;
}
}
public:
char* name;
};
void test_protoType(){
concretePrototype proto;
for (int i = 0;i < 100;++i) {
concretePrototype* clone = (concretePrototype*)proto.clone();
sprintf(clone->name, "%s %d", clone->name, i);
cout << clone->name << endl;
clone->freeClone();
free(clone);
}
}