首页 > 其他 > 详细

Simple screenshot that explains the singleton invocation.

时间:2014-03-09 01:37:46      阅读:398      评论:0      收藏:0      [点我收藏+]

Here is the code:

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

And the corresponds the code above:

bubuko.com,布布扣

Simple screenshot that explains the singleton invocation.,布布扣,bubuko.com

Simple screenshot that explains the singleton invocation.

原文:http://www.cnblogs.com/listened/p/3588778.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!