I am trying to create "reusable classes" if that is the correct term to use here.
Let’s say I am making a little game using tiles in a gridview. I have something like this:
enum gridTileClass { goblin, elf, dragon, dungeonFloor1 }
class gridTileData {
final gridTileClass type;
late final String tileImage;
int currentHealth;
gridTileData({
required this.type,
required this.tileImage,
required this.currentHealth,
});
}
But then when I am setting up the board, I am having to enter the data for every space on the grid manually, like this:
List<List<gridTileData?>> initializeBoard(int currentLevel) {
newBoard[0][0] = gridTileData(
type: gridTileClass.dungeonFloor1,
tileImage: './lib/images/dungeon_tile_1.png',
currentHealth: 0,
);
newBoard[0][1] = gridTileData(
type: gridTileClass.dungeonFloor1,
tileImage: './lib/images/dungeon_tile_1.png',
currentHealth: 0,
);
newBoard[0][2] = gridTileData(
type: gridTileClass.goblin,
tileImage: './lib/images/goblin1.png',
currentHealth: 0,
);
newBoard[0][3] = gridTileData(
type: gridTileClass.goblin,
tileImage: './lib/images/goblin1.png',
currentHealth: 0,
);
}
Now this is a simplified example, in reality it is far more tedious because I have instead of 3 properties for a class, more like 20 or more.
I would love to be able to instead do something like:
newBoard[0][1] = goblin;
somehow, since I have told it what a goblin is previously somewhere.
2
Answers
I recommend you use the Builder design pattern
you will be able to do something like this:
and the code for Builder and GoblinBuilder will be:
you can do the same for other characters and more.
for more info about the builder design pattern :
You can use the
factory
to pre-defined the class’s properties.And usage: