不同状态避免过长的分支判断语句可以使用
实例:计算缴税
级数
|
全年应纳税所得额
|
税率(%)
|
速算扣除数
|
1
|
不超过15000元的
|
5
|
0
|
2
|
超过15000元至30,000元的部分
|
10
|
750
|
3
|
超过30,000元至60,000元的部分
|
20
|
3750
|
4
|
超过60,000元至100,000元的部分
|
30
|
9750
|
5
|
超过100,000元的部分
|
35
|
14750
|
using System;
namespace 状态模式
{
class Program
{
static void Main(string[] args)
{
PayTaxes pt = new PayTaxes();
pt.Income = 5000;
pt.Execute();
pt.Income = 40000;
pt.Execute();
pt.Income = 20000;
pt.Execute();
pt.Income = 70000;
pt.Execute();
pt.Income = 150000;
pt.Execute();
pt.Income = 10000;
pt.Execute();
Console.Read();
}
}
public abstract class State
{
public abstract void Execute(PayTaxes p);
}
public class OneLevelState : State
{
public override void Execute(PayTaxes p)
{
if (p.Income <= 15000)
{
Console.WriteLine("收入{0},应缴税:{1}", p.Income, p.Income * 0.05);
}
else
{
p.SetState(new TwoLevelState());
p.Execute();
}
}
}
public class TwoLevelState : State
{
public override void Execute(PayTaxes p)
{
if (p.Income > 15000 && p.Income <= 30000)
{
Console.WriteLine("收入{0},应缴税:{1}", p.Income, p.Income * 0.1 - 750);
}
else
{
p.SetState(new ThreeLevelState());
p.Execute();
}
}
}
public class ThreeLevelState : State
{
public override void Execute(PayTaxes p)
{
if (p.Income > 30000 && p.Income <= 60000)
{
Console.WriteLine("收入{0},应缴税:{1}", p.Income, p.Income * 0.2 - 3750);
}
else
{
p.SetState(new FourLevelState());
p.Execute();
}
}
}
public class FourLevelState : State
{
public override void Execute(PayTaxes p)
{
if (p.Income > 60000 && p.Income <= 100000)
{
Console.WriteLine("收入{0},应缴税:{1}", p.Income, p.Income * 0.3 - 9750);
}
else
{
p.SetState(new FiveLevelState());
p.Execute();
}
}
}
public class FiveLevelState : State
{
public override void Execute(PayTaxes p)
{
if (p.Income > 100000)
{
Console.WriteLine("收入{0},应缴税:{1}", p.Income, p.Income * 0.35 - 14750);
}
else
{
p.SetState(new OneLevelState()); //最后一种状态还需要循环到第一种状态
p.Execute();
}
}
}
public class PayTaxes
{
private State current;
public PayTaxes()
{
current = new OneLevelState();
}
private double income;
public double Income
{
get { return income; }
set { income = value; }
}
public void SetState(State s)
{
current = s;
}
public void Execute()
{
current.Execute(this);
}
}
}