Here is the code:
1 /* 2 Some class,such as a config file,need to be only one.So we need to control the instance. 3 1,private the constructor and create only one instance in the class itself. 4 2,provide a method for the others to get the ‘only one‘ instance. 5 */ 6 package kju.obj; 7 8 import static kju.print.Printer.*; 9 public class SingletonDemo { 10 public static void main(String[] args) { 11 SingleConfig con01 = SingleConfig.getInstance(); 12 SingleConfig con02 = SingleConfig.getInstance(); 13 println("con01 color : " + con01.getColor()); 14 println("con02 set color : "); 15 con02.setColor("Blue"); 16 println("con01 color : " + con01.getColor()); 17 /* 18 con01 color : Orange 19 con02 set color : 20 con01 color : Blue 21 */ 22 } 23 } 24 25 class SingleConfig { 26 private String color = "Orange"; 27 private static SingleConfig s = new SingleConfig(); 28 29 private SingleConfig() {} 30 public static SingleConfig getInstance() { 31 return s; 32 } 33 34 public void setColor(String color) { 35 this.color = color; 36 } 37 38 public String getColor() { 39 return color; 40 } 41 }
And the corresponds the code above:
Simple screenshot that explains the singleton invocation.,布布扣,bubuko.com
Simple screenshot that explains the singleton invocation.
原文:http://www.cnblogs.com/listened/p/3588778.html