三層式系統架構-商業邏輯層
此介紹商業邏輯層需要的程式碼,
我個人對於商業邏輯層的定義為一個Tabel對映一個類別,
此類別需定義出Table的各欄位屬性,
及關於此Table的查詢、新增、修改、刪除等資料操作函式,
舉例
有一Table如下
欄位名稱 | 資料型態 |
CustomerID | Varchar(10) |
CompanyName | Varchar(50) |
0.類別名稱
End Class
1.定義私有變數
Private _CompanyName As String = ""
2.定義全域屬性
Get
Return _CustomerID
End Get
Set(ByVal value As String)
_CustomerID = value
End Set
End Property
Public Property CompanyName() As String
Get
Return _CompanyName
End Get
Set(ByVal value As String)
_CompanyName = value
End Set
End Property
3.建立清除函式
_CustomerID = ""
_CompanyName = ""
End Sub
4.建立New函式
Clear()
End Sub
5.定義查詢、新增、修改、刪除資料操作
Try
Return dalCustomers.GetData
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Public Function Insert() As Integer
Try
Return dalCustomers.Insert(Me)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Public Function Update() As Integer
Try
Return dalCustomers.Update(Me)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Public Shared Function Delete(ByVal Code As String) As Integer
Try
Return dalCustomers.Delete(Code)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
6.查詢資料使用物件回傳(非必要,個人使用方式)
GetCustomers函式會回傳一個bllCustomers陣列物件,
此用法為在使用欄位時是可以用屬性的方式取得值
Me.Clear()
If DT.Rows.Count > 0 Then
CustomerID = DT.Rows(0).Item("customerid").ToString
CompanyName = DT.Rows(0).Item("companyname").ToString
End If
End Sub
Public Shared Sub SetData(ByVal DT As DataTable, ByRef Data() As bllCustomers)
If DT.Rows.Count > 0 Then
For i As Integer = 0 To DT.Rows.Count - 1
If Data Is Nothing Then
ReDim Data(0)
Else
ReDim Data(Data.Length)
End If
Data(UBound(Data)) = New bllCustomers
Data(UBound(Data)).CustomerID = DT.Rows(i).Item("customerid").ToString
Data(UBound(Data)).CompanyName = DT.Rows(i).Item("companyname").ToString
Next
End If
End Sub
Public Shared Function GetCustomers() As bllCustomers()
Try
Dim tmCustomers() As bllCustomers = Nothing
Dim DT As DataTable = dalCustomers.GetData
SetData(DT, tmCustomers)
Return tmCustomers
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
創建一個商業邏輯層有很多程式碼其實是相似的,
故可以使用CodeSmith等軟體來產生相關程式碼,
再稍做修正,才不會浪費大量的時間。