I have a question regarding the Abstract Factory pattern sample code from the Design Patterns book.
The book presents a simplified and partial example of a maze game where there are walls and doors connecting rooms.
There is a basic MazeFactory class which has the following factory methods:
class MazeFactory {
public:
MazeFactory();
virtual Maze* MakeMaze() const { return new Maze; }
virtual Wall* MakeWall() const { return new Wall; }
virtual Room* MakeRoom(int n) const { return new Room(n); }
virtual Door* MakeDoor(Room* r1, Room* r2) const {
return new Door(r1, r2);
}
}
The author(s) then define a specialisation of MazeFactory:
class BombedMazeFactory : public MazeFactory {
BombedMazeFactory();
virtual Room* MakeWall() const { return new BombedWall; }
virtual Door* MakeRoom(int n) const { return new RoomWithABomb(n); }
};
I don't know exactly how RoomWithABomb should work but lets say it creates a room which has a 5% chance of containing a bomb and if you open a door which contains a bombed room you explode.
Now lets say the client creates their maze using the BombedMazeFactory class and they create some rooms. The rooms created are of type RoomWithABomb*, however the factory returns a Room*.
In order to implement some maze game logic I would assume you would need to check whether a room contains a bomb, but Room* has no knowledge about bombs. The only way we can find out if a room contains a bomb is to cast Room* to RoomWithABomb* which is bad practice right?
Is their example not very well thought out or is there some other way of handling cases such as this?
Aucun commentaire:
Enregistrer un commentaire