近期在机房合作开发中,对状态模式又有了进一步的理解,下面就以机房收费系统为例子来学习装套模式
''' <summary> ''' 定义一个状态变量 ''' </summary> Private State As LoginStateBLL ''' <summary> ''' 构造函数,初始化开始状态为判断用户名是否存在 ''' </summary> Public Sub New() State = New UserIsExistBLL() End Sub ''' <summary> ''' 设置状态 ''' </summary> ''' <param name="loginstate">传递用户登录过程中的状态</param> Public Function SetState(ByVal loginstate As LoginStateBLL) As LoginStateBLL State = loginstate '将当前状态值传递给全局变量state Return loginstate '将设置好的状态值返回 End Function ''' <summary> ''' 登录 ''' </summary> ''' <param name="enWork">工作记录实体</param> ''' <param name="enUser">用户实体</param> ''' <returns>登录成功返回true ''' 登录失败返回false</returns> ''' <remarks></remarks> Public Function Login(ByVal enWork As Entity.WorkEntity, ByVal enUser As Entity.UserEntiity) As Boolean Dim logins As LoginBLL = New LoginBLL '定义局部变量login 并实例化 Dim flag As Boolean = False '定义布尔类型变量 初始值为false '调用登陆状态类的方法 Try State.OnLog(logins, enWork, enUser) flag = True '登陆成功 Catch ex As Exception Throw New Exception(ex.Message) '捕捉登陆异常 ,并将异常抛出 End Try Return flag '将结果返回 End Function End Class
Public Class LoginStateBLL ''' <summary> ''' 登录状态 ''' </summary> ''' <param name="login">登录</param> ''' <param name="enWork">工作实体</param> ''' <param name="enUser">用户实体</param> Public Overridable Sub OnLog(ByVal login As LoginBLL, ByVal enWork As Entity.WorkEntity, ByVal enUser As Entity.UserEntiity) End Sub End Class
''' <summary> ''' 判断用户名是否存在 ''' </summary> Public Class UserIsExistBLL Inherits BLL.LoginStateBLL ''' <summary> ''' 登录状态 判断用户名是否存在 ''' </summary> ''' <param name="login">登录</param> ''' <param name="enWork">工作实体</param> ''' <param name="enUser">用户实体</param> Public Overrides Sub OnLog(ByVal login As LoginBLL, ByVal enWork As Entity.WorkEntity, ByVal enUser As Entity.UserEntiity) Dim factory As DFactory.DataAccess = New DFactory.DataAccess '定义并实例化工厂 Dim IUser As IDAL.IUser '定义接口 IUser = factory.GetUser() '调用工厂方法创建接口 Dim BTable As New DataTable '定义变量datatable BTable = IUser.IUserIsExit(enUser) '调用接口方法查询用户名是否存在 '判断用户名是否存在即表中是否含有所要查找的数据 If BTable.Rows.Count = 0 Then Throw New Exception("该用户名不存在") '抛出异常 Else login.SetState(New PwdIsExistBLL) '调用下一个状态 login.Login(enWork, enUser) '调用loginBLL中的登陆方法 End If End Sub End Class