完整的程式碼如下
1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : DP_StrategyPattern3_polymorphism_this.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to use Strategy Pattern with *this
7Release : 04/04/2007 1.0
8*/
9#include <iOStream>
10#include <string>
11
12using namespace std;
13
14class Grapher;
15
16class IShape {
17public:
18 virtual void draw(Grapher &grapher) const = 0;
19};
20
21class Grapher {
22private:
23 IShape *shape;
24 string text;
25
26public:
27 Grapher() {}
28 Grapher(IShape *shape, const char *text = "Hello Shape!!") : shape(shape), text(string(text)) {}
29
30public:
31 void drawShape() {
32 this->shape->draw(*this);
33 }
34
35 void setShape(IShape *shape, const char* text = "Hello Shape!!") {
36 this->text = text;
37 this->shape = shape;
38 }
39
40 string getText() const {
41 return this->text;
42 }
43};
44
45
46class Triangle : public IShape {
47public:
48 void draw(Grapher &grapher) const {
49 cout << "Draw " << grapher.getText() << " in Triangle" << endl;
50 }
51};
52
53class Circle : public IShape {
54public:
55 void draw(Grapher &grapher) const {
56 cout << "Draw " << grapher.getText() << " in Circle" << endl;
57 }
58};
59
60class Square : public IShape {
61public:
62 void draw(Grapher &grapher) const {
63 cout << "Draw " << grapher.getText() << " in Square" << endl;
64 }
65};
66
67
68int main() {
69 Grapher theGrapher(&Square());
70 theGrapher.drawShape();
71
72 theGrapher.setShape(&Circle(), "Hello C++!!");
73 theGrapher.drawShape();
74}
執行結果
Draw Hello Shape!! in Square
Draw Hello C++!! in Circle