例子
- 对一个价钱做不同策略;原价,打折,返利
public abstract class CashSuper
{
public abstract double AcceptCash(double money);
}
public class NormalCash : CashSuper
{
public override double AcceptCash(double money)
{
return money;
}
}
public class CashReturn : CashSuper
{
private double _moneyConditation;
private double _moneyReturn;
public CashReturn(double moneyConditation, double moneyReturn)
{
_moneyConditation = moneyConditation;
_moneyReturn = moneyReturn;
}
public override double AcceptCash(double money)
{
if (money >= _moneyConditation)
{
return money - _moneyReturn;
}
else
{
return money;
}
}
}
public class CashRebate : CashSuper
{
private double _moneyRebate;
public CashRebate(double moneyRebate)
{
_moneyRebate = moneyRebate;
}
public override double AcceptCash(double money)
{
return money * _moneyRebate;
}
}
public class MoneyContext
{
private CashSuper _cashSuper;
public MoneyContext(CashSuper cashSuper)
{
_cashSuper = cashSuper;
}
public double GetMoney(double money)
{
return _cashSuper.AcceptCash(money);
}
}
static void Main(string[] args)
{
var normal = new MoneyContext(new NormalCash());
Console.WriteLine($"正常:{normal.GetMoney(50)}");
var rebate = new MoneyContext(new CashRebate(0.5));
Console.WriteLine($"打折:{rebate.GetMoney(50)}");
var return_ = new MoneyContext(new CashReturn(20, 10));
Console.WriteLine($"返利:{return_.GetMoney(50)}");
Console.WriteLine("Hello World!");
}