【前言】
策略模式是区别对待的典型, 它存在的意义就在于让系统对不同身份的“人”,给出相应不同的算法,比如商场购物, 高级会员7折,普通会员9折, 非会员客户原价,这种情况下给商场设计收银系统用策略模式就很实用。我们这次的机房收费系统重构也遇到了类似的问题, 就是算钱时,不同的人要有不同的收费方式。 所以这次就用上了策略模式。
【正文】
【策略模式UML图】
先来看一下策略模式一般情况下的uml图:
大体上一致,我们再来看一下我在机房中的uml图:
【具体代码】
下面我们来看一下具体的代码:
CashContext:
Public MustInherit Class Exit_CashSuperBLL
Public MustOverride Function CountConsumeCash(ByVal time As Integer) As Integer
End Class
Exit_GeneralUserStrategy:
Public Class Exit_GeneralUserStrategy : Inherits BLL.Exit_CashSuperBLL
Public Overrides Function CountConsumeCash(time As Integer) As Integer
Dim CostMoney As Integer
CostMoney = time * entity.SharedX.MinuteCharge
Return CostMoney
End Function
End Class
Public Class Exit_VIPUserStrategy : Inherits Exit_CashSuperBLL
Public Overrides Function CountConsumeCash(time As Integer) As Integer
Dim CostMoney As Integer
CostMoney = time * entity.SharedX.MinuteCharge * 0.8 ‘会员打八折
Return CostMoney
End Function
End Class
Imports System.Reflection
Imports BLL
Public Class Exit_CashContextBLL ' 利用策略模式对金额进行计算
Private _Super As Exit_CashSuperBLL
Private _strStudentLevel As String '存储学生等级的字段
Public Property StudentLevel As String
Get
Return _strStudentLevel
End Get
Set(value As String)
_strStudentLevel = value
End Set
End Property
Private Property cashSuper() As Exit_CashSuperBLL
Get
Return _Super
End Get
Set(value As Exit_CashSuperBLL)
_Super = value
End Set
End Property
Public Sub SelectStragy() '通过学生身份来确定收费策略
Try
Dim AssmeblyName As String = "JFloginBLL"
Dim className As String = "BLL.Exit-" + _strStudentLevel + "UserStrategy"
Me.cashSuper = CType(Assembly.Load("JFloginBLL").CreateInstance(className), Exit_CashSuperBLL) ’通过反射机制确定具体策略
Catch ex As Exception
Throw
End Try
End Sub
Public Function GetResult(ByVal time As Integer) '计算金额
Try
Dim returnMoney As Integer
returnMoney = cashSuper.CountConsumeCash(time)
Return returnMoney
Catch ex As Exception
Throw
End Try
End Function
End Class
【总结】
设计模式的使用能让我们的程序变得更清爽,耦合度更低,想添加功能就添加功能。