I'm working on a web game that has several different types of bricks so I decided to implement the factory pattern. The bricks are stored in a database (must have) and then build using the factory with the properties from the result set.
Factory:
public class BrickBuilder {
public Brick build(String type, int width, int height, String image) {
Brick brick = null;
switch (type) {
case "energy":
brick = new EnergyBrick(width, height, image);
break;
...
return brick;
}
Parent class:
public abstract class Brick {
// Properties
public Brick(String type, int width, int height, String image){
this.type = type;
this.width = width;
this.height = height;
this.image = image;
}
public abstract void construct(double x, double y, int hitCount);
Concrete implementation:
public class EnergyBrick extends Brick {
// Properties
public EnergyBrick(int width, int height, String image) {
super("energy", width, height, image);
}
@Override
public void construct(int hitCount, double x, double y) {
this.hitCount = hitCount;
this.x = x;
this.y = y;
}
SQL ResultSet to Brick used by getAll, getByName, ... in the repository
private Brick rsToBrick(ResultSet rs) throws SQLException {
String type = rs.getString("name");
int width = rs.getInt("width");
int height = rs.getInt("height");
String image = rs.getString("image");
Brick brick = BUILDER.build(type, width, height, image);
return brick;
}
Generate bricks
private void generateBricks() {
List<Brick> databaseBricks = BrickRepositorySQL.getInstance().getAll();
bricks = new ArrayList<>();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 14; j++) {
chance = Math.floor(Math.random() * 5);
if (chance == 4) {
continue;
}
if (chance == 3 || chance == 2 || chance == 1) {
// Create new concrete brick with tesame properties as in the array
x = j * 140;
y = i * 80;
brick.construct(x, y, 1);
if (chance == 0) {
x = j * 140;
y = i * 80;
// Create new concrete brick with tesame properties as in the array
brick.construct(x, y, 1);
}
bricks.add(brick);
}
}
}
}
I have an ArrayList that has all the different types of bricks from the database. I would like to take one of the bricks out of this array, for example the EnergyBrick and then create a new EnergyBrick with the same properties and use the construct method on this brick to set the x and y coordinates with the hitCount.
Things I have tried:
databaseBricks.get(brickIndex) and then use the construct method on this brick, problem is that all the bricks have tesame reference
repository.getByName("energy") works perfectly but takes way too long to query the database for each brick
Aucun commentaire:
Enregistrer un commentaire