class Grapher {
public:
typedef void (*pfDraw)();
Grapher(pfDraw draw = 0) : _draw(draw) {}
void drawShape() const { if (_draw) _draw(); }
void setShape(pfDraw draw) { _draw = draw; }
protected: pfDraw _draw;
};
class Triangle { public: static void draw() { cout << "Draw Triangle" << endl; } };
class Circle { public: static void draw() { cout << "Draw Circle" << endl; } };
class Square { public: static void draw() { cout << "Draw Square" << endl; } };
int main() {
Grapher grapher(Square::draw); grapher.drawShape();
grapher.setShape(Circle::draw); grapher.drawShape();
}
Draw Square
Draw Circle
本質:介面定義函數簽名 → 函數指標類型定義簽名。所有傳入函數必須符合指標類型。C++ 函數指標啟發 C# Delegate 實現 Strategy。