开发者

GoF's implementation of the Prototype pattern

开发者 https://www.devze.com 2023-04-01 18:54 出处:网络
(This question is more for the people who have access to the book, It\'s hard to put it into context otherwise)

(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

精彩评论

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