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

我的Design Pattern之旅[1]:Strategy Pattern (OO)(4)

編輯:關於C語言

ISO C++ by Function Pointer

1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename  : DP_StrategyPattern_FunctionPointer.cpp
5Compiler  : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to use Strategy Pattern by function pointer
7Release   : 03/31/2007 1.0
8      : 07/08/2007 2.0
9      : 07/10/2007 3.0
10*/
11#include <iOStream>
12
13using namespace std;
14
15class Grapher {
16public:
17 typedef void (*pfDraw)();
18 Grapher(pfDraw draw = 0) : _draw(draw) {}
19
20public:
21 void drawShape() const;
22 void setShape(pfDraw draw);
23
24protected:
25 pfDraw _draw;
26};
27
28void Grapher::drawShape() const {
29 if (_draw)
30  _draw();
31}
32
33void Grapher::setShape(pfDraw draw) {
34 _draw = draw;
35}
36
37class Triangle {
38public:
39 static void draw();
40};
41
42void Triangle::draw() {
43 cout << "Draw Triangle" << endl;
44}
45
46class Circle {
47public:
48 static void draw();
49};
50
51void Circle::draw() {
52 cout << "Draw Circle" << endl;
53}
54
55class Square {
56public:
57 static void draw();
58};
59
60void Square::draw() {
61 cout << "Draw Square" << endl;
62}
63
64int main() {
65 Grapher grapher(Square::draw);
66 grapher.drawShape();
67
68 grapher.setShape(Circle::draw);
69 grapher.drawShape();
70}

執行結果

Draw Square
Draw Circle

說穿了,本來只是本來由interface定義function的signature,現在改由16行的

typedef void (*pfDraw)();

定義pfDraw這個function pointer型別,所有要傳進的的function必須符合這個function pointer型別才可。

既然ISO C++可以用function pointer實現strategy pattern,就讓我想到C#的delegate了。delegate是C#對function pointer和observer pattern的實現,理應可用delegate來實現strategy pattern。

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