【机房重构】策略模式

谁借莪1个温暖的怀抱¢ 2022-07-26 08:46 273阅读 0赞
  1. 刚开始学习策略模式的时候虽然书是看懂了但是有一个问题就是不知道如何去实际的应用,通过机房重构中下机消费金额的计算懂得了如何的去使用这个策略模式。

策略模式:(Strategy)

它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变法,不会影响到使用算法的客户。

策略模式:

Center

策略在机房中的应用:

BLL层:

BC_CashContext类

  1. Public Class BC_CashContext
  2. Dim cashsuper As BC_CashSuper '定义抽象类
  3. Public Sub New(ByVal cardType As String) '参数是收费类型
  4. Select Case cardType
  5. Case "固定用户"
  6. cashsuper = New BC_CashVip() '创建固定用户收费类型
  7. Case "临时用户"
  8. cashsuper = New BC_CashNormal() '临时用户收费
  9. Case Else
  10. cardType = Nothing
  11. End Select
  12. End Sub
  13. Public Function GetResult(ByVal Time As Integer) As Single
  14. '调用相关的消费处理类计算收费方法
  15. Return cashsuper.GetConsumeMoney(Time)
  16. End Function
  17. End Class

BC_CashSuper类

  1. Public MustInherit Class BC_CashSuper
  2. Public MustOverride Function GetConsumeMoney(ByVal Time As Integer) As Single ‘处理请求的抽象方法
  3. End Class

BC_CashNormal类

  1. Public Class BC_CashNormal : Inherits BC_CashSuper
  2. Dim Enbasicinfo As New Entity.BasicInfo '定义实体
  3. Dim table As New DataTable
  4. Dim baseinfo As New BLL.BBasicInfo '用于查询基础数据
  5. Dim NorCash As Single
  6. Public Overrides Function GetConsumeMoney(Time As Integer) As Single
  7. '调用查询方法获取数据,且赋值给实体泛型集合
  8. table = baseinfo.CheckLimitCash1(Enbasicinfo)
  9. Enbasicinfo.Rate = table.Rows(0).Item(1) '给变量赋值(用户每小时费用)
  10. NorCash = CInt(Enbasicinfo.Rate)
  11. Dim consumecash As Single
  12. consumecash = Trim(CSng(Time) * CSng(NorCash / 60))
  13. Return consumecash
  14. End Function
  15. End Class

BC_CashVip类

  1. Public Class BC_CashVip : Inherits BC_CashSuper
  2. '调用查询方法获取数据,且赋值给实体泛型集合
  3. Dim baseinfo As New BLL.BBasicInfo '用于查询基础数据
  4. Dim Enbasicinfo As New Entity.BasicInfo '定义实体
  5. Dim table As DataTable
  6. '定义实体泛型
  7. Dim VipCash As Single '定义变量存放固定用户每小时费用
  8. Public Overrides Function GetConsumeMoney(Time As Integer) As Single
  9. table = baseinfo.CheckLimitCash1(Enbasicinfo)
  10. Enbasicinfo.Rate = table.Rows(0).Item(0) '给变量赋值(用户每小时费用)
  11. VipCash = CInt(Enbasicinfo.Rate)
  12. Dim consumeCash As Single
  13. consumeCash = Trim(CSng(Time) * (VipCash / 60)) '计算消费金额
  14. Return consumeCash
  15. End Function
  16. End Class

UI层

  1. '计算消费的金额, 将消费时间传入 调用策略模式
  2. Dim cashcontext As New BLL.BC_CashContext(father.type.Trim)
  3. onlineInfo1.ConsumeTime = txtCumeTime.Text.ToString
  4. Dim consumecash As Single = cashcontext.GetResult(onlineInfo1.ConsumeTime)

使用策略模式为我们省了很多的时间,简化了代码量,最主要的还是简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。

发表评论

表情:
评论列表 (有 0 条评论,273人围观)

还没有评论,来说两句吧...

相关阅读

    相关 机房重构】——报表

        从第一版的机房收费系统就有报表的使用,当时确实是第一次接触到报表这个东西,因为VB中没有报表,所以当初调用的是其他的报表工具。这次机房重构中再次用到报表,看过一些关于机

    相关 机房重构】总结

    机房收费个人版算是磕磕绊绊完成了,这里话不多说,收获的东西,遇到的困难,只有自己才能懂得。总结一下重构过程中的问题,不足及学到的东西。 一.验收问题 那天紧赶慢赶的完