基於Session的單件(Singleton)對象<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Session Based Singleton Object
Use singleton objects stored in the Session object to organize and cleanup session based information
背景
在ASP.Net 當中,Session 對象經常被用來存儲一個站點用戶的信息,這對
於一個站點的個人用戶來說是很有效的方法。Session通過使用一個關鍵字
作爲它的索引。當應用這種方式使用它時,它可以引導大量的session名
稱. 我們也可以建立一個singleton 對象來根據具體的項目進行分組,用
來存儲給對象和給定的關鍵字。singleton 是一個很普通的設計模式,它規
定瞭如何保證在任意時間內只存在一個類的唯一的實例。
Singleton Session對象的優點
- 以組織爲目的對session 中的項進行分組。
- 對在短時間過程中的一系列頁面特別有用,如在一個站點註冊。一旦
- 過程結束,對象可以從session 中清除,所以內存可以再次被請求
(使用服務器資源更佳)。
- 修改session信息的影響力分析更容易。
- 一個站點的用戶域的信息被誤用(如使用得當,比起只使用名稱來確
認更加清晰)。
Singleton Session對象的缺點
- 很難查看session 中的個人信息的數量
- ASP.Net 的跟蹤結果不能顯示對象內的值
- 當使用進程以外的方式存儲session(影響串行化)時,會導致性能下降。
實現
建立一個singleton類:
VB.net代碼:
Public Class singleton 'Name that will be used as key for Session object Private Const SESSION_SINGLETON As String = "SINGLETON" 'Variables to store the data (used to be individual 'session key/value pairs) Dim _lastName As String = "" Dim _firstName As String = ""
Public Property LastName() As String Get Return _lastName End Get Set(ByVal Value As String) _lastName = Value End Set End Property Public Property FirstName() As String Get Return _firstName End Get Set(ByVal Value As String) _firstName = Value End Set End Property
'Private constructor so cannot create an instance ' without using the correct method. This is ' this is critical to properly implementing ' as a singleton object, objects of this ' class cannot be created from outside this ' class
Private Sub New() End Sub 'Create as a static method so this can be called using 'just the class name (no object instance is required). 'It simplifies other code because it will always return 'the single instance of this class, either newly created 'or from the session Public Shared Function GetCurrentSingleton() As singleton Dim oSingleton As singleton If System.Web.HttpContext.Current.Session(SESSION_SINGLETON) Is Nothing Then 'No current session object exists, use private constructor to 'create an instance, place it into the session oSingleton = New singleton System.Web.HttpContext.Current.Session(SESSION_SINGLETON) = oSingleton Else 'Retrieve the already instance that was already created oSingleton = CType(System.Web.HttpContext.Current.Session(SESSION_SINGLETON), singleton) End If 'Return the single instance of this class that was stored in the session Return oSingleton End Function End Class
|
C#代碼:
singleton oSingleton = singleton.GetCurrentSingleton(); oSingleton.FirstName = "Robert";
oSingleton.LastName = "Boedigheimer"; |
這項技術可以在給定的類中存儲更多的變量,也可以被一系列的Web頁面來使
用,執行一定的過程。另外一個高級使用方法是在一個Web站點的過程中使用,通過對
singleton對象引用的移除,所有的內存中請求的session變量可以很容易的清除。 類可以
實現一個客戶端用來清除引用的方法。可以命名爲Dispose,類似在.NET 模式中提供的清
除對象的方法。
public static void Dispose() { //Cleanup this object so that GC can reclaim space System.Web.HttpContext.Current.Session.Remove(SESSION_SINGLETON); } |