当我们有一个对象时,想基于该对象生成一个一模一样的对象,有人说,那我直接拷贝构造一个不就行了,专门搞个设计模式岂不是脱裤子放屁?确实,比如我有一个Cat c = new Cat;想再造一个直接拷贝构造即可,但是如果我用 Abstruct Animal = new Cat; 我只有一个抽象类的指针却想生成一个一模一样的猫,貌似拷贝构造就解决不了问题了

再举个例子,比如画图工具,一般都会提供右键选中已有图形,复制一份的功能,但是如果这个图形只是一个抽象类的指针,应该如何复制出一个一样的形状?

我们设计一个抽象的类shape,提供一个纯虚函数clone,它的返回类型为shape* ,每个继承它的类,无论是圆形还是方形必须重写该方法,当我们拿到一个shape*指针时,无论它实际是个圆还是个方形,只要调用clone一定可以获取一个一模一样的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>

class shape {
public:
virtual shape* clone() = 0;
virtual void draw() = 0;
virtual ~shape() {}
};

class circle : public shape {
public:
circle() {
std::cout << "circle created" << std::endl;
}
circle(const circle&) {
std::cout << "circle copied" << std::endl;
}
shape* clone() override {
return new circle(*this);
}
void draw() override {
std::cout << "draw circle" << std::endl;
}
};

class rectangle : public shape {
public:
rectangle() {
std::cout << "rectangle created" << std::endl;
}
rectangle(const rectangle&) {
std::cout << "rectangle copied" << std::endl;
}
shape* clone() override {
return new rectangle(*this);
}
void draw() override {
std::cout << "draw rectangle" << std::endl;
}
};

int main() {
shape* circle1 = new circle();
shape* rectangle1 = new rectangle();

shape* circle2 = circle1->clone();
shape* rectangle2 = rectangle1->clone();

circle1->draw();
rectangle1->draw();
circle2->draw();
rectangle2->draw();

delete circle1;
delete rectangle1;
delete circle2;
delete rectangle2;

return 0;
}