Definition: The builder pattern encapsulates the construction of a product that can be constructed in steps.
Usage: Use the builder pattern as an alternative to the abstract factory pattern when the objects being created are complex enough to require multiple steps to create.
interface DungeonBuilder {
Floor addOneFloor()
Room addOneRoom(Floor floor, Room previousRoom, various parameters)
addMonster(Room room, various parameters)
addNPC(Room room, various parameters)
addTrap(Room room, various parameters)
addTreasure(Room room, various parameters)
}
class DungeonBuilderExample {
DungeonBuilderExample(DungeonBuilder builder) {
//first floor
Floor floor1 = builder.addOneFloor();
Room entryRoom = builder.addOneRoom(floor1, null, ...);
builder.addNPC(entryRoom, ...);
Room westRoom = builder.addOneRoom(floor1, entryRoom, ...);
Room northRoom = builder.addOneRoom(floor1, entryRoom, ...);
Room eastRoom = builder.addOneRoom(floor1, entryRoom, ...);
//more stuff for the first floor
//second floor
Floor floor2 = builder.addOneFoor();
//more stuff for the second floor
}
}
The dungeon builder interface builds a dungeon, one floor at a time. Much more work would need to be done to make this anything worthwhile, but this should be enough to illustrate the builder pattern. An abstract factory could never work because each floor is too complex to include all the data as parameters. In real life, the most likely solution to this problem would be to store all the data in a file using some kind of dungeon builder program.
Copyright (C) 2008 Steven Fletcher. All rights reserved.