转自:http://blog.csdn.net/andylin02/archive/2008/11/14/3302034.aspx
- using System;
- namespace CashSystem
- {
- //线程类
- class CRunMain
- {
- public static void ShowMessage()
- {
- Console.WriteLine("-----------------please input your choise: ------------");
- Console.WriteLine("/t/t0. quite");
- Console.WriteLine("/t/t1. pay cash noremally");
- Console.WriteLine("/t/t2. pya cash in 8 rebate");
- Console.WriteLine("/t/t3. pay cash in after 300 return 100");
- Console.WriteLine("-------------------------------------------------------");
- }
- public static int Main()
- {
- CCashContext objCont = new CCashContext();
- CCashSuper objCash = null;
- while (true)
- {
- int nChoice = 0;
- int nCount = 0;
- double duMoney = 0.0;
- double duPrice = 0.0;
- ShowMessage();
- nChoice = Convert.ToInt32(Console.ReadLine());
- switch (nChoice)
- {
- case 0:
- Console.WriteLine("press any key to quit!");
- Console.Read();
- return 0;
- case 1:
- objCash = new CCashNormal();
- break;
- case 2:
- objCash = new CCashRebate(0.8);
- break;
- case 3:
- objCash = new CCashReturn(300, 100);
- break;
- default:
- objCash = null;
- break;
- }
- if (null == objCash)
- {
- Console.WriteLine("input error!");
- continue;
- }
- //set cash object
- objCont.SetBehavior(objCash);
- Console.WriteLine("please input price: ");
- duPrice = Convert.ToDouble(Console.ReadLine());
- Console.WriteLine("please input count: ");
- nCount = Convert.ToInt32(Console.ReadLine());
- duMoney = duPrice * nCount;
- Console.WriteLine("the properly money you should pay is " + objCont.GetResult(duMoney));
- }
- }
- };
- //收费策略Context
- class CCashContext
- {
- //设置策略行为,参数为具体的现金收费子类(正常,打折或返利)
- public void SetBehavior(CCashSuper objCash)
- {
- this.m_objCash = objCash;
- }
- public double GetResult(double duMoney)
- {
- if (null == this.m_objCash)
- {
- Console.WriteLine("null == m_objCash");
- return 0;
- }
- return this.m_objCash.AcceptCash(duMoney);
- }
- private CCashSuper m_objCash;
- };
- abstract class CCashSuper
- {
- public abstract double AcceptCash(double duMoney);
- };
- class CCashReturn:CCashSuper
- {
- public CCashReturn(double duCondition, double duReturn)
- {
- this.m_duCondition = duCondition;
- this.m_duReturn = duReturn;
- }
- public override double AcceptCash(double duMoney)
- {
- if (duMoney > this.m_duCondition)
- {
- duMoney -= this.m_duReturn;
- }
- return duMoney;
- }
- private double m_duCondition = 0.0;
- private double m_duReturn = 0.0;
- };
- class CCashNormal:CCashSuper
- {
- public override double AcceptCash(double duMoney)
- {
- return duMoney;
- }
- };
- class CCashRebate:CCashSuper
- {
- public CCashRebate(double duRebate)
- {
- this.m_duRebate = duRebate;
- }
- public override double AcceptCash(double duMoney)
- {
- return duMoney * this.m_duRebate;
- }
- private double m_duRebate;
- };
- }