单例作为全局变量的一种方式

本文内容:利用单例的方式实现一个作为全局变量的简单方法。用代码说明,比较清晰一点。

UserPool.cs

View Code
 1 class UserPool
2 {
3 publicstaticreadonly UserPool GlobalUserPool =new UserPool();
4 private Hashtable ht =new Hashtable();
5
6 private UserPool()
7 {
8 }
9 publicvoid Add(string key, UserInformation userInfor)
10 {
11 lock (ht.SyncRoot)
12 {
13 ht[key] = userInfor;
14 }
15 }
16
17 publicvoid Remove(string key)
18 {
19 if (ht.ContainsKey(key))
20 {
21 lock (ht.SyncRoot)
22 {
23 if (ht.ContainsKey(key))
24 {
25 ht.Remove(key);
26 }
27 }
28 }
29 }
30
31 public UserInformation GetUserInfo(string key)
32 {
33 if (ht.ContainsKey(key))
34 {
35 lock (ht.SyncRoot)
36 {
37 if (ht.ContainsKey(key))
38 {
39 return ht[key] as UserInformation;
40 }
41 else
42 {
43 returnnull;
44 }
45 }
46 }
47 else
48 {
49 returnnull;
50 }
51 }
52
53 publicbool ContainsKey(string key)
54 {
55 return ht.ContainsKey(key);
56 }
57 }

UserInformation.cs

View Code
1 class UserInformation
2 {
3 publicstring[] UserFriends { get; set; }
4 publicstring KeyGuid { get; set; }
5 publicstring Name { get; set; }
6 }
posted @ 2011-08-19 09:47  走过留痕  阅读(408)  评论(0编辑  收藏  举报