Welcome

首页 / 软件开发 / C# / 我的Design Pattern之旅[3]:使用template改進Strategy Pattern(OO)

我的Design Pattern之旅[3]:使用template改進Strategy Pattern(OO)2010-03-29 cnblogs 在(原创) 我的Design Pattern之旅:Strategy Pattern (初级) (Design Pattern) (C++) (OO C++) (Template C++)中,我们使用了strategy pattern让Grapher能画Triangle、Circle和Square

因为需求再次改变,:D,我们希望Grapher能将文字印在各Shape中,执行结果如下

Draw Hello Shape!! in Square
Draw Hello C++!! in Circle

为了达到此需求,我们可以将IShape interface改成

class IShape {
public:
virtual void draw(const char *text) const = 0;
};

但若将来需求再改变,希望画的不是文字,而是一张图片,那interface又必须再变动,为了一劳永逸,我们会将整个物件传给各strategy,IShape interface改成如下

class IShape {
public:
virtual void draw(Grapher &grapher) const = 0;
};

Grapher::drawShpae()将*this传给各strategy

void drawShape() {
this->shape->draw(*this);
}