【机房重构】策略模式

     刚开始学习策略模式的时候虽然书是看懂了但是有一个问题就是不知道如何去实际的应用,通过机房重构中下机消费金额的计算懂得了如何的去使用这个策略模式。

   策略模式:(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)

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





    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 18
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值