系列文章回顾
原型模式使用原型实例指定创建对象的种类,并且通过拷贝原型对象创建新的对象。原型模式的关键点在于原型实例与实例的复制,实例的克隆分为深拷贝与浅拷贝。
原型模式使用的是深拷贝, 使用原型模式复制对象不会调用类的构造方法。
01_Prototype
原型模式包含三种角色:
优点:
缺点:
02_Prototype_UML
#-*- coding: utf-8 -*-
'''
原型模式
'''
from copy import copy, deepcopy
class Prototype(object):
"""原型类"""
def __init__(self):
super(Prototype, self).__init__()
def clone(self):
pass
class ConcretePrototype1(Prototype):
"""具体原型类"""
def __init__(self):
print("Create ConcretePrototype1")
def clone(self):
print("Copy ConcretePrototype1...")
return deepcopy(self)
class ConcretePrototype2(Prototype):
"""具体原型类"""
def __init__(self):
print("Create ConcretePrototype2")
def clone(self):
print("Copy ConcretePrototype2...")
return deepcopy(self)
if __name__ == '__main__':
p1 = ConcretePrototype1()
cp1 = p1.clone()
p2 = ConcretePrototype2()
cp2 = p2.clone()
输出结果:
Create ConcretePrototype1
Copy ConcretePrototype1...
Create ConcretePrototype2
Copy ConcretePrototype2...
#ifndef PROTOTYPE_H
#define PROTOTYPE_H
#include <iostream>
using namespace std;
class Prototype
{
public:
virtual ~Prototype() {}
virtual Prototype* clone() const = 0;
protected:
Prototype() {}
};
class ConcretePrototype1 : public Prototype
{
public:
ConcretePrototype1() {
cout << "Create ConcretePrototype1." << endl;
}
ConcretePrototype1(const ConcretePrototype1& other) {
cout << "Copy ConcretePrototype1..." <<endl;
}
~ConcretePrototype1() {}
ConcretePrototype1* clone() const {
return new ConcretePrototype1(*this);
}
};
class ConcretePrototype2 : public Prototype
{
public:
ConcretePrototype2() {
cout << "Create ConcretePrototype2." << endl;
}
ConcretePrototype2(const ConcretePrototype2& other) {
cout << "Copy ConcretePrototype2..." <<endl;
}
~ConcretePrototype2() {}
ConcretePrototype2* clone() const {
return new ConcretePrototype2(*this);
}
};
#endif // PROTOTYPE_H
#include <iostream>
#include "prototype.h"
using namespace std;
int main()
{
Prototype* p1 = new ConcretePrototype1();
Prototype* cp1 = p1->clone();
Prototype* p2 = new ConcretePrototype2();
Prototype* cp2 = p2->clone();
delete p1;
delete cp1;
delete p2;
delete cp2;
return 0;
}
输出结果:
Create ConcretePrototype1.
Copy ConcretePrototype1...
Create ConcretePrototype2.
Copy ConcretePrototype2...