Pali
Pali

Reputation: 1347

Factory Pattern - Type variables

First, my english is not the best and I haven't found what I was looking for, maybe because I didn't knew how to ask google in english or my nativ language > java beginner!

I am developing a little game where I use many types of "bombs", for this I am using an abstract class Bomb and an enum BombType. Each type of bomb should have its own values, for example a rangeand a timer. Now I am struggling with the bussiness logic how I should use bombs and how I should handle their types. Is it better to make use of their type or their class?

What I have:

public enum BombType {

    // pass object or what else?
    DEFAULT(new Default()),
    NUKE(new Nuke());

    public final int range;
    public final long timer;

    BombType(Bomb paramBomb) {
        this.range = paramBomb.range;
        this.timer = paramBomb.timer;
    }
}

public abstract class Bomb {

    final BombType bombType;
    final int range;
    final long timer;

    protected Bomb(BombType paramBombType) {
        this.bombType = paramBombType;
        this.range = paramBombType.range;
        this.timer = paramBombType.timer;
    }

}

public class Default extends Bomb {
    protected Default() {
        super(BombType.DEFAULT);
    }
}

So my question is how should I handle the different types of bombs in the outter world?

Option 1, by class:

public void doSomethingWithTheBomb(Bomb bomb) {
    switch(bomb.bombType) {
        case DEFAULT: 
            Default defaultBomb = (Default) bomb;
            logger.log(defaultBomb.range);
            logger.log(defaultBomb.timer);
            {...}
            break;
        case NUKE: 
            Nuke nukeBomb = (Nuke) bomb;
            logger.log(nukeBomb.range);
            logger.log(nukeBomb.timer);
            {...}
            break;
        defrault:
            break;
    }
}

Option 2, by type:

public void doSomethingWithTheBomb(Bomb bomb) {
    logger.log(bomb.bombType.range);
    logger.log(bomb.bombType.timer);
    {...}
}

Upvotes: 0

Views: 62

Answers (1)

Burkhard
Burkhard

Reputation: 14738

Option 1 is bad, since you duplicate code.
Option 2 is better.

I would add a getRange() and getTimer() to the abstract Bomb class, and depending obn what needs to be done, a doSomething() method. That way you can have your Bomb (whichever it is) do something.

Upvotes: 3

Related Questions