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原則。