开发者

GoF's implementation of the Prototype pattern

(This question is more for the people who have access to the book, It's hard to put it into context otherwise)

I've been reading through the GoF's 'Design Patterns' book and there's a sentence that confuses me a little, under 'Creational Patterns->Prototype->Sample code' (page 124).

Near the bottom of the page, there is the implemententation for BombedWall, which as I understand is a concrete prototype, as it inherits from Wall, and redefines the Clone() virtual function. BombedWall also defines another method, HasBomb(), unknown to any clients using the regular Wall interface.

The only way that BombedWall is stored in MazePrototypeFactory (the Prototype client) is as a Wall* (returned from BombedWall::Clone), and the only way to get to HasBomb() afterwards, as far as I understand, is to perform a downca开发者_如何学Cst on that Wall* to a BombedWall* (dynamic or static, depending on whether I know the type), and then I can access the HasBomb() method.

This all seemed fine to me; but then later the author says (same page, last sentence, 2nd last paragraph):

"Clients should never have to downcast the return value of Clone to the desired type"

What? Then how am I supposed to get to HasBomb()?

I must be missing something...


I gave an answer and totally rewrote it now :)

Basically, the MazePrototypeFactory only knows about the base classes it can use. It doesn't know anything about any of the subclasses you are going to make, but it still should be able to put any possible subclass out there into the maze.

The pattern basically ensures MazeFactory will get a pointer of a type that it understands, Wall, than cause the MazeFactory to need to be modified to be able to produce objects of all the subclasses.

MazeFactory is the client referred to on p 124. It doesn't need to know about HasBomb in order to build the maze.


My guess is that this method only exists to indicate that BombedWall is a different class with extended public interface. Hovewer, this interface is not used in the context of the sample: the maze building algorithm does not differentiate types of walls, while other subsystems (for example, rendering engine) may do so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜