本文承接前一篇,示範在不使用 Template 的情況下,如何利用多型與 *this 指標,讓 Grapher 將自身傳遞給策略物件,使策略能存取 Grapher 的公開介面(如 getText())。
IShape 介面的 draw() 參數固定為 Grapher &,策略類別(Triangle、Circle、Square)繼承 IShape 並實作繪圖邏輯:
class IShape {
public:
virtual void draw(Grapher &grapher) const = 0;
};
#include <iostream>
#include <string>
using namespace std;
class Grapher;
class IShape {
public:
virtual void draw(Grapher &grapher) const = 0;
};
class Grapher {
private:
IShape *shape;
string text;
public:
Grapher() {}
Grapher(IShape *shape, const char *text = "Hello Shape!!")
: shape(shape), text(string(text)) {}
void drawShape() {
this->shape->draw(*this);
}
void setShape(IShape *shape, const char* text = "Hello Shape!!") {
this->text = text;
this->shape = shape;
}
string getText() const { return this->text; }
};
class Triangle : public IShape {
public:
void draw(Grapher &grapher) const {
cout << "Draw " << grapher.getText() << " in Triangle" << endl;
}
};
class Circle : public IShape {
public:
void draw(Grapher &grapher) const {
cout << "Draw " << grapher.getText() << " in Circle" << endl;
}
};
class Square : public IShape {
public:
void draw(Grapher &grapher) const {
cout << grapher.getText() << " in Square" << endl;
}
};
int main() {
Grapher theGrapher(&Square());
theGrapher.drawShape();
theGrapher.setShape(&Circle(), "Hello C++!!");
theGrapher.drawShape();
}
Draw Hello Shape!! in Square
Draw Hello C++!! in Circle
此版本透過多型機制,讓 Grapher 在執行期動態切換繪圖策略。雖然運作正常,但 IShape 仍強綁定 Grapher 型別,後續文章將引入 Template 解決此限制。