机房重构—策略模式简单用

来源:互联网 发布:电视机看电视软件 编辑:程序博客网 时间:2024/05/01 13:12

         在机房重构过程中下机敲的比较顺利,当然了,这是没有用设计模式的情况下,后来通过看别人的博客觉得自己的代码太low了,对于设计模式还是学以致用的好,于是决定用策略模式去计算不同等级用户的消费金额。

       策略模式

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


       其实最重要的是使具体算法能够随时相互替换,在机房收费中固定用户和临时用户的收费方式肯定是不同的,那么就把固定用户和临时用户的收费算法封装起来,选择哪种用户类型便去实例化其对应的算法,从而避免去使用大量的switch条件分支,减少各种算法类与使用算法类之间的耦合,使得算法更易扩展。

       机房代码:

       CashContext

    Public Class CashContext        Dim cashsuper As CashSuper        Public Sub New(ByVal CardType As String) '参数是收费类型            Select Case CardType                Case "固定用户"                    cashsuper = New FixUser()  '实例化具体策略                Case "临时用户"                    cashsuper = New tmpUser()                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

         CashSuper

    '抽象策略    Public MustInherit Class CashSuper        Public MustOverride Function GetConsumeMoney(ByVal Time As Integer) As Single    End Class
        FixUser

    '具体策略:固定用户和临时用户收费计算    Public Class FixUser : Inherits CashSuper        Dim BasicBll As New BLL.BasicDataBLL        Dim BasicData As New Model.ModelBasicData        Dim table As New DataTable        Dim strFixRate As Single        Public Overrides Function GetConsumeMoney(Time As Integer) As Single            table = BasicBll.InquireBasicData(BasicData)            strFixRate = Trim(Int(table.Rows(0).Item("FixUserCost")))            Dim consumeCash As Single            consumeCash = Trim(Val(strFixRate * Int(Val(Time / 60))))            Return consumeCash        End Function    End Class
        tmpUser

    Public Class tmpUser : Inherits CashSuper        Dim BasicBll As New BLL.BasicDataBLL        Dim BasicData As New Model.ModelBasicData        Dim table As New DataTable        Dim strTmpRate As Single        Public Overrides Function GetConsumeMoney(Time As Integer) As Single            table = BasicBll.InquireBasicData(BasicData)            strTmpRate = Trim(Int(table.Rows(0).Item("tmpUserCost")))            Dim consumeCash As Single            consumeCash = Trim(Val(strTmpRate * Int(Val(Time / 60))))            Return consumeCash        End Function    End Class
        UI调用(消费时间已知—consume)

    Dim csuper As New BLL.CashContextBLL.CashContext(strKind)    Dim consumecash As Single = csuper.GetResult(consume)
        其实单从代码量来看,使用设计模式后的代码要比之前多很多,但却做到了解耦,几千行代码的程序也许还体现不出其价值,但以后我们毕竟要接触大的项目,所以,成长从现在开始~

      

2 0
原创粉丝点击