系列第三篇的起點:需求變更要求 Grapher 能在各形狀中印出文字。若直接修改 IShape::draw(const char*),未來若需繪製圖片而非文字,介面又得再改。為一勞永逸,決定將整個 Grapher 物件(*this)傳給策略,讓策略自行取所需資料。
virtual void draw(const char *text) const = 0; — 僅支援文字,擴充性差。virtual void draw(Grapher &grapher) const = 0; — 傳遞完整物件,策略可呼叫 grapher.getText() 或未來任何公開方法。class IShape {
public:
virtual void draw(Grapher &grapher) const = 0;
};
void Grapher::drawShape() {
this->shape->draw(*this); // 傳遞 this 指標
}
此設計奠定後續引入 Template 進行泛型化的基礎,解決策略與特定 Context 類別緊耦合的問題。