網上搜到這個資料.
加以修改加工一下,發布.感謝原作者的付出:http://singlewolf.javaeye.com/blog/173877
Singleton類之所以是private型構造方法,就是為了防止其它類通過new來創建實例,即如此,那我們就必須用一個static的方法來創建一個實例(為什么要用static的方法?因為既然其它類不能通過new來創建實例,那么就無法獲取其對象,那么只用有類的方法來獲取了)
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()的時候,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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

打印結果:












private static Singleton instance;
public static Singleton getInstance()
這2個是靜態的
1.定義變量的時候是私有,靜態的:private static Singleton instance;
2.定義私有的構造方法,以防止其它類通過new來創建實例;
3.定義靜態的方法public static Singleton getInstance()來獲取對象.instance = new Singleton();