我正在创作一本书,我对全局化变量(对象)感兴趣。
在一个项目中,我可以使用Singletone: 但是如果我在我的库中使用它并给它一个值,如果在我的项目中我咨询的值总是为0。
库:
public class Globals{
private static Globals instance;
// Global variable
private int data;
// Restrict the constructor from being instantiated
private Globals(){}
public void setData(int d){
this.data=d;
}
public int getData(){
return this.data;
}
public static synchronized Globals getInstance(){
if(instance==null){
instance=new Globals();
}
return instance;
}
/*Then write your methods here*/
public void yourMethod(){}
}
LIBRARY:Class ExampleLib
Globals g = Globals.getInstance();
g.setData(120));
MYPROJECT
Globals g = Globals.getInstance();
System.out.println(g.getData()); // show 0