mercredi 26 octobre 2016

Java: link object to a variable in another object

This is a bit difficult to explain so I wrote up and example to illustrate the concept. In the following example I have a stock class which models the figures that affect a stock simulation program. I also have a MarketModifier class which represents events which would affect the stocks in different ways.

public class ExampleArea  
{
    public static void main(String cvhfg[]) 
    {  
        Stock test = new Stock(1f,1f,1f,1f);
        MarketModifier worldEvent = 
            new MarketModifier("Bad publicity",-2.5f,"publicOpinion");
    }   
}
class MarketModifier
{
    public MarketModifier(String name, float modifier, String variable) {
        super();
        this.name = name;
        Modifier = modifier;
        this.variable = variable;
    }
    String name;
    float Modifier;
    String variable;
}
class Stock
{
    public Stock(float value, float integrity, float publicPresence, float publicOpinion) {
        super();
        this.value = value;
        this.integrity = integrity;
        this.publicPresence = publicPresence;
        this.publicOpinion = publicOpinion;
    }
    float value;
    float integrity;
    float publicPresence;
    float publicOpinion;
    //...other variables...
}

My question is how would I link the marketModifer to the variable in the Stock model (in the example above it is "publicOpinion" set in the "variable" String) without using a string. Strings have the problem of possibly mistyping them, and I would need a switch to identify which variable the modifier was affecting.

I thought of using an enum but I would still need a switch table to check them and I would also have to update the enum values every time a stock has a different variable which could be affected (there could be additional variables in the subclasses of Stock). The other option I thought of was reflection but this solution, though I think it would work, seems overly complicated, and adds more difficulty in reading than it solves.

So again, is there a better way to link the an object to the variable(s) that it affects in another object (maybe some kind of observer/watcher pattern?).

Aucun commentaire:

Enregistrer un commentaire