java - Singleton between many classes? -
i've got quite disturbing problem singleton in project. created class called singleton (how creative) variable string name;
then created class called player take name of user.
and main class want save data kept in singleton.
the problem is, saves name of user if take in main class..it seems not work in other classes.
what reason ? how fix it? advice :)
here's singleton class:
private string name; public void setname(string name) { this.name = name; } public string getname( ) { return this.name; } private static singleton instance = null; protected singleton() { } public static singleton getinstance() { if(instance == null) { instance = new singleton(); } return instance; }
this class take name of user:
public class newmain { public newmain() { string u_name="agrfd"; singleton.getinstance().setname(u_name); } }
and here main class save data singleton (here try print make sure works):
public class newmain1 { public static void main(string[] args) { singleton singleton = new singleton(); system.out.println(singleton.getinstance().getname()); } }
you using different instances of singleton design object. use singleton pattern.
exemplary implementation:
public class classicsingleton { private static classicsingleton instance = null; protected classicsingleton() { // exists defeat instantiation. } public static classicsingleton getinstance() { if(instance == null) { instance = new classicsingleton(); } return instance; } }
your usage should be:
public class newmain1 { public static void main(string[] args) { new newmain(); // execute constructor setter on creation first system.out.println(singleton.getinstance().getname()); } }
Comments
Post a Comment