程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 我的Design Pattern之旅[3]:使用template改進Strategy Pattern(OO)(2)

我的Design Pattern之旅[3]:使用template改進Strategy Pattern(OO)(2)

編輯:關於C語言

完整的程式碼如下

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved