網(wǎng)上搜到這個(gè)資料.
加以修改加工一下,發(fā)布.感謝原作者的付出:http://singlewolf.javaeye.com/blog/173877
Singleton類之所以是private型構(gòu)造方法,就是為了防止其它類通過(guò)new來(lái)創(chuàng)建實(shí)例,即如此,那我們就必須用一個(gè)static的方法來(lái)創(chuàng)建一個(gè)實(shí)例(為什么要用static的方法?因?yàn)榧热黄渌惒荒芡ㄟ^(guò)new來(lái)創(chuàng)建實(shí)例,那么就無(wú)法獲取其對(duì)象,那么只用有類的方法來(lái)獲取了)
1
class 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
43
public class danli
{
44
45
public static void main(String[] args)
{
46
47
Singleton s1 = Singleton.getInstance();
48
49
//再次getInstance()的時(shí)候,instance已經(jīng)被實(shí)例化了
50
51
//所以不會(huì)再new,即s2指向剛初始化的實(shí)例
52
53
Singleton s2 = Singleton.getInstance();
54
55
System.out.println(s1==s2);
56
57
s1.say();
58
59
s2.say();
60
61
//保證了Singleton的實(shí)例被引用的都是同一個(gè),改變一個(gè)引用,則另外一個(gè)也會(huì)變.
62
63
//例如以下用s1修改一下say的內(nèi)容
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
打印結(jié)果:
true

單例模式原版

單例模式原版

hey is me Senngr

hey is me Senngr

true

private static Singleton instance;
public static Singleton getInstance()
這2個(gè)是靜態(tài)的
1.定義變量的時(shí)候是私有,靜態(tài)的:private static Singleton instance;
2.定義私有的構(gòu)造方法,以防止其它類通過(guò)new來(lái)創(chuàng)建實(shí)例;
3.定義靜態(tài)的方法public static Singleton getInstance()來(lái)獲取對(duì)象.instance = new Singleton();