单例模式讲解

网上搜到这个资料.

加以修改加工一下,发布.感谢原作者的付出:http://singlewolf.javaeye.com/blog/173877

Singleton类之所以是private型构造方法,就是为了防止其它类通过new来创建实例,即如此,那我们就必须用一个static的方法来创建一个实例(为什么要用static的方法?因为既然其它类不能通过new来创建实例,那么就无法获取其对象,那么只用有类的方法来获取了)

 1class Singleton {   
 2
 3     private static Singleton instance;  
 4
 5     private static String str="单例模式原版" ;
 6
 7 
 8
 9     private Singleton(){}   
10
11     public static Singleton getInstance(){   
12
13         if(instance==null){   
14
15             instance = new Singleton();   
16
17         }
   
18
19         return instance;   
20
21     }
   
22
23     public void say(){   
24
25         System.out.println(str);   
26
27     }
  
28
29     public void updatesay(String i){
30
31           this.str=i;
32
33           
34
35          
36
37     }
 
38
39}
   
40
41  
42
43public class danli{   
44
45    public static void main(String[] args) {   
46
47        Singleton s1 = Singleton.getInstance();   
48
49        //再次getInstance()的时候,instance已经被实例化了   
50
51        //所以不会再new,即s2指向刚初始化的实例   
52
53        Singleton s2 = Singleton.getInstance();   
54
55        System.out.println(s1==s2);   
56
57        s1.say();   
58
59        s2.say();   
60
61        //保证了Singleton的实例被引用的都是同一个,改变一个引用,则另外一个也会变.
62
63        //例如以下用s1修改一下say的内容
64
65        s1.updatesay("hey is me Senngr");   
66
67        s1.say();  
68
69        s2.say(); 
70
71        System.out.println(s1==s2); 
72
73    }
   
74
75}

76

 打印结果:
true

单例模式原版

单例模式原版

hey is me Senngr

hey is me Senngr

true

private static Singleton instance;
public static Singleton getInstance()
这2个是静态的 

1.定义变量的时候是私有,静态的:private static Singleton instance;
2.定义私有的构造方法,以防止其它类通过new来创建实例;
3.定义静态的方法public static Singleton getInstance()来获取对象.instance = new Singleton();
原文地址:https://www.cnblogs.com/redcoatjk/p/3562421.html