(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 downcast 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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top