物件導向基礎觀念
- 類別:物件的藍圖,定義屬性與方法。
- 實例:具體可互動的物件。
- 封裝:隱藏內部實作,僅公開介面(Property Let/Get)。
- 多型:同名方法,不同實作。
- 繼承:ASP 不支援繼承,但可用組合模式替代。
實戰範例:論壇會員資訊類別
<%
Class BlueIdeaUser
Private m_name, m_point, m_sex, m_level
'--- 唯讀屬性 ---
Property Get UserName
UserName = m_name
End Property
Property Get UserSex
UserSex = m_sex
End Property
Property Get UserPoint
UserPoint = m_point
End Property
Property Get UserLevel
UserLevel = m_level
End Property
'--- 寫入屬性(含驗證) ---
Property Let UserName(val)
m_name = Trim(val)
If m_name = "" Then m_name = "未註冊用戶"
End Property
Property Let UserSex(val)
Dim v : v = KillInt(val, 0, 0)
If v = 0 Then m_sex = "男" Else m_sex = "女"
End Property
Property Let UserPoint(val)
m_point = KillInt(val, 0, 0)
End Property
'--- 私有輔助函數 ---
Private Function KillInt(v, defVal, minVal)
If Not IsNumeric(v) Then v = defVal
If v <= 0 Then v = minVal
KillInt = Int(Left(v, 5))
End Function
Private Sub CalcLevel()
If m_point < 500 Then m_level = "初級會員"
ElseIf m_point <= 1000 Then m_level = "高級會員"
Else m_level = "終極會員"
End If
End Sub
'--- 公開方法 ---
Public Sub ShowInfo()
CalcLevel()
Response.Write "<h5>以下顯示 <font color=red>" & m_name & "</font> 的資料:</h5>"
Response.Write "<h5>性別: <font color=red>" & m_sex & "</font></h5>"
Response.Write "<h5>積分: <font color=red>" & m_point & "</font></h5>"
Response.Write "<h5>級別: <font color=red>" & m_level & "</font></h5>"
End Sub
End Class
%>
使用方式
<%
Set user = New BlueIdeaUser
user.UserName = Request("id")
user.UserSex = Request("sex")
user.UserPoint = Request("point")
user.ShowInfo()
%>
優勢總結
- 資料保護:私有變數外部不可直接存取,透過 Property 驗證賦值。
- 邏輯封裝:等級計算、資料清洗集中在類別內部。
- 可維護性:修改顯示格式只需改類別,呼叫端零修改。
- 團隊協作:設計師負責前端,工程師負責類別,介面溝通清晰。
雖 ASP 不支援繼承,但善用類別封裝已能大幅提升代碼組織品質,是邁向現代化架構的關鍵步驟。