Implementing Factory and Mediator Patterns for a Tower Defense Game

The Attack method in BotanicRepeater retrieves a bullet via the mediater:

@Override
public void attack(ICharacter target) {
    Bullet projectile = Mediator.getInstance().fetchBullet("SingleBullet", launchPoint, new Point(1300, launchPoint.y));
}

In BotanicRepeaterFactory, create a plant character using the factory method:

@Override
public ICharacter generateCharacter(Point startLocation, int rowIndex) {
    CharacterBaseAttr baseProperties = AttributeFactory.retrieveBaseAttributes("BotanicRepeater");
    CharacterAttr attributes = new CharacterAttr(baseProperties, 0);
    BotanicRepeater plant = new BotanicRepeater(attributes, startLocation, rowIndex);
    Mediator.getInstance().registerPlant(plant);
    return plant;
}

BulletFactory handles bullet creation and activation:

if (type.equals("SingleBullet")) {
    Bullet projectile = new Bullet.Builder(type)
            .setImagePath("/data/workspace/myshixun/images/Plants/PB00.gif")
            .setVelocity(25)
            .setLifespan(1.0f)
            .setImpactDamage(10)
            .setExplosionImage("/data/workspace/myshixun/images/Plants/PeaBulletHit.gif")
            .build();
    projectile.activate(startPos, destination);
    Mediator.getInstance().addBullet(projectile);
    return projectile;
}

ZombieNormalFactory implemetns the factory method for zombies:

@Override
public ICharacter generateCharacter(Point startLocation, int rowIndex) {
    CharacterBaseAttr baseProperties = AttributeFactory.retrieveBaseAttributes("ZombieNormal");
    CharacterAttr attributes = new CharacterAttr(baseProperties, 2);
    ZombieNormal enemy = new ZombieNormal(attributes, startLocation, rowIndex);
    Mediator.getInstance().registerEnemy(enemy);
    return enemy;
}

In Mediator, manage bullet retrieval and creation:

public Bullet fetchBullet(String type, Point startPos, Point destination) {
    Bullet projectile = characterSystem.retrieveBullet(type);
    if (projectile != null) {
        projectile.activate(startPos, destination);
        addBullet(projectile);
    } else {
        projectile = BulletFactory.createBullet(type, startPos, destination);
    }
    return projectile;
}

Tags: java Design Patterns Factory Method Mediator Pattern game development

Posted on Sun, 19 Jul 2026 16:27:04 +0000 by dalex