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

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

編輯:關於C語言

ISO C++ by Interface

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

執行結果

Draw Square
Draw Circle

67行和70行可以看到strategy pattern的美,可以動態的換演算法,如同plugin一樣,且若將來擴充其他shape,只需加上新的class實做IDrawStrategy,其他程式都不用再改,符合OCP原則。

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