Rule mode,
Rule Mode
1. All algorithms perform the same job, but their implementations are different. They call all algorithms in the same way to reduce coupling and facilitate unit testing.
2. When the client needs to apply different rules at different times, the policy mode can be used.
III. different from a simple factory: In the simple factory mode, the client uses the factory and algorithm classes. If the algorithm class is changed, the client will be affected. however, in the policy mode, the client only uses the policy class and has nothing to do with the algorithm class.
Implementation Code of the Mode:
Public abstract class CashSpuer
{
Public abstract double acceptCash (double money );
}
Public class CashNormal
{
Public override double acceptCash (double money)
{
Return money;
}
}
Public class CashRebate: CashSpuer
{
Private double moneyRebate = 1d;
Public CashRebate (string moneyRebate)
{
This. moneyRebate = double. Parse (moneyRebate );
}
Public override double acceptCash (double money)
{
Return money * moneyRebate;
}
}
Public class CashReturn: CashSpuer
{
Private double moneyCondition;
Private double moneyReturn;
Public CashReturn (string moneyCondition, string moneyReturn)
{
This. moneyCondition = double. Parse (moneyCondition );
This. moneyReturn = double. Parse (moneyReturn );
}
Public override double acceptCash (double money)
{
If (money> moneyCondition)
{
Return money-Math. Floor (money/moneyCondition) * moneyReturn;
}
Else
Return money;
}
}
Public class CashContext
{
Private CashSpuer cs;
Public CashContext (string type)
{
Switch (type)
{
Case "normal charges ":
Cs = new CashNormal ();
Break;
Case "discount ":
Cs = new CashRebate ("0.8 ");
Break;
Case "three hundred minus one hundred ":
Cs = new CashReturn ("300", "100 ");
Break;
}
}
Public double acceptCash (double money)
{
Return cs. acceptCash (money );
}
}
Mode call:
Double total = 0d;
Private void btnOK_Click (object sender, EventArgs e)
{
CashContext cc = null;
Double totalPrice = 0d;
Cc = new CashContext (cbxType. SelectedItem. ToString ());
TotalPrice = cc. acceptCash (double. Parse (txtPrice. Text) * double. Parse (txtNums. Text ));
Total = total + totalPrice;
TxtTotal. Text = total. ToString ();
ListBox1.Items. add (string. format ("unit price: {0} quantity: {1} calculation method: {2} Subtotal: {3}", txtPrice. text. padRight (3), txtNums. text. padRight (3), cbxType. selectedItem. toString (). padRight (12), totalPrice. toString ()));
}
Private void Form1_Load (object sender, EventArgs e)
{
CbxType. Items. AddRange (new object [] {"normal charges", "three hundred discount", "One hundred minus "});
CbxType. SelectedIndex = 0;
}