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。