Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton with dynamic variable

Tags:

java

I need to call function to recalculate argument from different place of program {different classes}. I need to recalculate with different coefficient which can be changed in running time. Simple example: new_value = old_value * coefficient.

At the moment I have class which hold those coefficient and has methods which are doing that recalculation. Disadvantage: I need to pass that instance of class to each place where I want to used it.

This is my singleton:

public class Converter {
    private double              lbU_2_U;
    private static Converter    instance    = new Converter();

    public Converter() {
        lbU_2_U = 1;
    }

    public static Converter getInstance() {
        return instance;
    }

    public void updateVelocityCoeficient(double lb_2_p) {
        lbU_2_U = lb_2_p;
    }

    public double velToP(double lbU) {
        return lbU_2_U * lbU;
    }

    public double velToLB(double u) {
        return u / lbU_2_U;
    }
}

so, advantage now will be that in anywhere in program I can write

newVelocity = Converter.getInstance().velToP(velocity)

Go for forward, I would do something like this:

newVelocity = Converter.velToP(velocity)

so I am thinking about change my Singleton to this:

public class Converter {
    private double              lbU_2_U;
    private static Converter    instance    = new Converter();

    public Converter() {
        lbU_2_U = 1;
    }

    public static Converter getInstance() {
        return instance;
    }

    public static void updateVelocityCoeficient(double lb_2_p) {
        instance.lbU_2_U = lb_2_p;
    }

    public static double velToP(double lbU) {
        return instance.lbU_2_U * lbU;
    }

    public static double velToLB(double u) {
        return u / instance.lbU_2_U;
    }
}

What do you thing? I am not sure if this is effective, if I can used this in multipleThread app, and if this is correct way of using Singleton.

thank you

like image 743
janci Avatar asked Sep 17 '26 18:09

janci


1 Answers

This is not a good scenario to use the Singleton pattern.

Have a look into these answers: When should the Singleton pattern NOT be used?

like image 176
cahen Avatar answered Sep 20 '26 07:09

cahen