【个人机房重构】策略模式在下机


【前言】

      策略模式是区别对待的典型, 它存在的意义就在于让系统对不同身份的“人”,给出相应不同的算法,比如商场购物, 高级会员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


Exit_VIPUserStrategy

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


  Exit_CashContextBLL :

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



【总结】

      设计模式的使用能让我们的程序变得更清爽,耦合度更低,想添加功能就添加功能。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农胖虎-java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值