dimanche 24 novembre 2019

Singleton Pattern not returning same object in my Java Code

Is there any wrong in my Code. Because the variable not changing its value while applying Singleton Pattern.

My Code :

class Singleton{

private final static Supplier<Singleton> INSTANCE = Singleton::new;
private int variable = 33;


public static synchronized Supplier<Singleton> getInstance() { 
    return INSTANCE;
}

void print(){
    System.out.println(variable);
}

void change(int variable){
    this.variable = variable;
}

}

public class Design {

public static void main(String[] args) {
    Singleton.getInstance().get().print(); // print 33
    Singleton.getInstance().get().change(99);
    Singleton.getInstance().get().print(); // need to print 99 but it prints 33

}

}

Please correct me Guys, if I'm wrong in implement Singleton Pattern.

Aucun commentaire:

Enregistrer un commentaire