简体   繁体   English

工厂模式-类型变量

[英]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! 首先,我的英语不是最好的,而且我还没有找到我想要的东西,可能是因为我不知道如何用英语或我的母语来问Google> Java初学者!

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 . 我正在开发一个小游戏,其中使用了多种类型的“炸弹”,为此,我正在使用抽象类Bomb和枚举BombType Each type of bomb should have its own values, for example a range and a timer . 每种炸弹应具有自己的值,例如rangetimer 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 ? 利用它们的typeclass更好吗?

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: 选项1,按类别:

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: 选项2,按类型:

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

Option 1 is bad, since you duplicate code. 选项1不好,因为您重复了代码。
Option 2 is better. 选项2更好。

I would add a getRange() and getTimer() to the abstract Bomb class, and depending obn what needs to be done, a doSomething() method. 我将getRange()getTimer()到抽象的Bomb类中,并根据obn需要做的事情,使用doSomething()方法。 That way you can have your Bomb (whichever it is) do something. 这样,您就可以让炸弹(无论是哪个炸弹)做点什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM