【机房重构】策略模式
刚开始学习策略模式的时候虽然书是看懂了但是有一个问题就是不知道如何去实际的应用,通过机房重构中下机消费金额的计算懂得了如何的去使用这个策略模式。
策略模式:(Strategy)
它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变法,不会影响到使用算法的客户。
策略模式:
策略在机房中的应用:
BLL层:
BC_CashContext类
Public Class BC_CashContext
Dim cashsuper As BC_CashSuper '定义抽象类
Public Sub New(ByVal cardType As String) '参数是收费类型
Select Case cardType
Case "固定用户"
cashsuper = New BC_CashVip() '创建固定用户收费类型
Case "临时用户"
cashsuper = New BC_CashNormal() '临时用户收费
Case Else
cardType = Nothing
End Select
End Sub
Public Function GetResult(ByVal Time As Integer) As Single
'调用相关的消费处理类计算收费方法
Return cashsuper.GetConsumeMoney(Time)
End Function
End Class
BC_CashSuper类
Public MustInherit Class BC_CashSuper
Public MustOverride Function GetConsumeMoney(ByVal Time As Integer) As Single ‘处理请求的抽象方法
End Class
BC_CashNormal类
Public Class BC_CashNormal : Inherits BC_CashSuper
Dim Enbasicinfo As New Entity.BasicInfo '定义实体
Dim table As New DataTable
Dim baseinfo As New BLL.BBasicInfo '用于查询基础数据
Dim NorCash As Single
Public Overrides Function GetConsumeMoney(Time As Integer) As Single
'调用查询方法获取数据,且赋值给实体泛型集合
table = baseinfo.CheckLimitCash1(Enbasicinfo)
Enbasicinfo.Rate = table.Rows(0).Item(1) '给变量赋值(用户每小时费用)
NorCash = CInt(Enbasicinfo.Rate)
Dim consumecash As Single
consumecash = Trim(CSng(Time) * CSng(NorCash / 60))
Return consumecash
End Function
End Class
BC_CashVip类
Public Class BC_CashVip : Inherits BC_CashSuper
'调用查询方法获取数据,且赋值给实体泛型集合
Dim baseinfo As New BLL.BBasicInfo '用于查询基础数据
Dim Enbasicinfo As New Entity.BasicInfo '定义实体
Dim table As DataTable
'定义实体泛型
Dim VipCash As Single '定义变量存放固定用户每小时费用
Public Overrides Function GetConsumeMoney(Time As Integer) As Single
table = baseinfo.CheckLimitCash1(Enbasicinfo)
Enbasicinfo.Rate = table.Rows(0).Item(0) '给变量赋值(用户每小时费用)
VipCash = CInt(Enbasicinfo.Rate)
Dim consumeCash As Single
consumeCash = Trim(CSng(Time) * (VipCash / 60)) '计算消费金额
Return consumeCash
End Function
End Class
UI层
'计算消费的金额, 将消费时间传入 调用策略模式
Dim cashcontext As New BLL.BC_CashContext(father.type.Trim)
onlineInfo1.ConsumeTime = txtCumeTime.Text.ToString
Dim consumecash As Single = cashcontext.GetResult(onlineInfo1.ConsumeTime)
使用策略模式为我们省了很多的时间,简化了代码量,最主要的还是简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
还没有评论,来说两句吧...