首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

我的 Design Pattern 之旅 [1]:Strategy Pattern (2) - C++ Interface 經典實現

     編輯:關於C語言

Strategy Pattern ISO C++ 經典介面實現:虛函數多態與 OCP 原則完美結合

核心代碼


class IDrawStrategy { public: virtual void draw() const = 0; };

class Grapher {
public: Grapher(IDrawStrategy* drawStrategy = 0) : _drawStrategy(drawStrategy) {}
void drawShape() const { if (_drawStrategy) _drawStrategy->draw(); }
void setShape(IDrawStrategy* drawStrategy) { _drawStrategy = drawStrategy; }
protected: IDrawStrategy* _drawStrategy;
};

class Triangle : public IDrawStrategy { public: void draw() const { cout << "Draw Triangle" << endl; } };
class Circle : public IDrawStrategy { public: void draw() const { cout << "Draw Circle" << endl; } };
class Square : public IDrawStrategy { public: void draw() const { cout << "Draw Square" << endl; } };

int main() {
    Grapher grapher(&Square()); grapher.drawShape();
    grapher.setShape(&Circle()); grapher.drawShape();
}

執行結果


Draw Square
Draw Circle

動態換演算法如 Plugin 般靈活。擴充新 Shape 僅需實作 IDrawStrategy,既符合 OCP Closed for Modification 又符合 Open for Extension。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved