1.窗体
2.上下文
Public Class CashContext
Private mCashsuper As CashSuper
Public Sub New(ByVal type As String)
Select Case type
Case "正常收费"
Dim cs0 As CashNormal = New CashNormal("正常收费")
mCashsuper = cs0
Case "满300返100"
Dim cs1 As CashReturn = New CashReturn("300", "100")
mCashsuper = cs1
Case "打8折"
Dim cs2 As CashRebate = New CashRebate("0.8")
mCashsuper = cs2
End Select
End Sub
Public Function GetResult(ByVal money As Double) As Double
Return mCashsuper.acceptCash(money)
End Function
End Class
3.抽象策略和具体策略
'现金收费抽象类
Public Class CashSuper
Public Overridable Function acceptCash(ByVal money As Double) As Double
Return money
End Function
End Class
'正常收费
Public Class CashNormal
Inherits CashSuper
Dim myMoneyRebate As Double
Public Sub New(ByVal moneyRebate As String)
myMoneyRebate = 1
End Sub
Public Overrides Function acceptCash(ByVal money As Double) As Double
Return money * myMoneyRebate
End Function
End Class
'打折收费
Public Class CashRebate
Inherits CashSuper
Dim myMoneyRebate As Double
Public Sub New(ByVal moneyRebate As String)
myMoneyRebate = Double.Parse(moneyRebate)
End Sub
Public Overrides Function acceptCash(ByVal money As Double) As Double
Return money * myMoneyRebate
End Function
End Class
Public Class CashReturn
Inherits CashSuper
Private myMoneyCondition As Double
Private myMoneyReturn As Double
Public Sub New(ByVal moneycondition As String, ByVal moneyReturn As String)
myMoneyCondition = Double.Parse(moneycondition)
myMoneyReturn = Double.Parse(moneyReturn)
End Sub
Public Overrides Function acceptCash(ByVal money As Double) As Double
Dim result As Double
result = money
If money >= myMoneyCondition Then
result = money - Math.Floor(money / myMoneyCondition) * myMoneyReturn
End If
Return result
End Function
End Class
4.客户端代码
Public Class Form1
Dim total As Double = 0
Private Sub txtOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtOk.Click
Dim myCashcontext As New CashContext(ComboBox1.SelectedItem.ToString)
Dim totalPrice As Double
Dim tmp As Double = Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtCount.Text)
totalPrice = myCashcontext.getresult(tmp)
ListBox1.Items.Add("单价:" + txtPrice.Text + "数量:" + txtCount.Text + "合计:" + totalPrice.ToString)
total += totalPrice
lblTotlePrice.Text = total.ToString
End Sub
End Class