In my design Journey: Strategy pattern (primary) (C + +) (OO C + +) (Template C + +), we used strategy pattern to let graph Er can draw triangle, circle and square
Because the need to change again,:D, we hope that Grapher will be able to print the text in each shape, the implementation of the results are as follows
Draw Hello Shape!! in Square
Draw Hello C++!! in Circle
In order to achieve this demand, we can change the IShape interface
class IShape {
public:
virtual void draw(const char *text) const = 0;
};
But if the future needs to change, hope to draw is not text, but a picture, that interface must again change, in order to once and for all, we will pass the entire object to the Strategy,ishape interface into the following
class IShape {
public:
virtual void draw(Grapher &grapher) const = 0;
};
Grapher::drawShpae()将*this传给各strategy
void drawShape() {
this->shape->draw(*this);
}