Here is the code:
/*
Some class,such as a config file,need to be only one.So we need to control the instance.
1,private the constructor and create only one instance in the class itself.
2,provide a method for the others to get the 'only one' instance.
*/
package kju.obj; import static kju.print.Printer.*;
public class SingletonDemo {
public static void main(String[] args) {
SingleConfig con01 = SingleConfig.getInstance();
SingleConfig con02 = SingleConfig.getInstance();
println("con01 color : " + con01.getColor());
println("con02 set color : ");
con02.setColor("Blue");
println("con01 color : " + con01.getColor());
/*
con01 color : Orange
con02 set color :
con01 color : Blue
*/
}
} class SingleConfig {
private String color = "Orange";
private static SingleConfig s = new SingleConfig(); private SingleConfig() {}
public static SingleConfig getInstance() {
return s;
} public void setColor(String color) {
this.color = color;
} public String getColor() {
return color;
}
}
And the corresponds the code above: