GoF implementation of the Prototype template

(This question is more suitable for people with access to the book, it is difficult to put them in context otherwise)

I read the book “GoF Design Templates” and the sentence, which confuses me a bit, in the section “Creation Templates → Prototype-> Code Example” (p. 124).

At the bottom of the page there is an implementation for BombedWall , which, as I understand it, is a specific prototype, since it inherits from Wall and redefines the virtual function Clone() . BombedWall also defines another HasBomb() method, unknown to any clients using the normal Wall interface.

The only way to save BombedWall in MazePrototypeFactory (Prototype client) as Wall* (returns from BombedWall::Clone ) and the only way to get to HasBomb() after that, as far as I can understand, is to do downcast on Wall* to BombedWall* (dynamic or static, depending on whether I know the type), and then I can access the HasBomb() method.

It all seemed beautiful to me; but then the author says (same page, last sentence, second paragraph):

"Customers will never have to lower the Clone return value to the desired type."

What? Then how can I get to HasBomb() ?

Something is missing me ...

+4
source share
2 answers

I gave an answer and completely rewrote it now :)

Basically, MazePrototypeFactory only knows about the base classes that it can use. He does not know anything about any of the subclasses that you are going to create, but he should still be able to put any possible subclass into the maze.

The template basically ensures that MazeFactory receives a pointer to the type that it understands Wall, which makes MazeFactory need to be modified in order to be able to create objects of all subclasses.

MazeFactory is the client mentioned on page 124. It does not need to know about HasBomb in order to build the maze.

+1
source

I assume that this method exists only to indicate that BombedWall is another class with an extended public interface. Hovewer, this interface is not used in the context of sampling: the maze algorithm does not distinguish between types of walls, while other subsystems (for example, the rendering engine) can do this.

0
source

Source: https://habr.com/ru/post/1369662/


All Articles