返回

策略模式

策略模式简介

策略模式与工厂模式十分相似,但是也有着实质性的不同。 传入一个参数》策略模式类》同一个API可以得到不同的答案。 例如两万块钱,如果是个人交税,需要交18%的税,如果是企业则须交30%的税;那么我们可以通过策略模式得到不同商户所需上交税。

简单代码例子

public class StrageBase
{
    public virtual void Caculate()
    {
        Debug.Log("==");
    }
}
//个人所得税计算
public class PersonStrage : StrageBase
{
    float myTax;
    public PersonStrage(float tmpTax)
    {
        myTax = tmpTax;
    }
    public override void Caculate()
    {
        myTax = myTax * 0.18f;
        Debug.Log("个人交税PersonStrage==" + myTax);
    }
}
//企业所得税计算
public class CompananyStrage : StrageBase
{
    float myTax;
    public CompananyStrage(float tax)
    {
        myTax = tax;
    }
    public override void Caculate()
    {
        myTax = myTax * 0.3f;
        Debug.Log("企业交税CompananyStrage==" + myTax);
    }
}
//计算器
public class Caculatestarge
{
    public void Caculatestage(StrageBase tmpStarge)
    {
        tmpStarge.Caculate();
    }
}

public class TeachStrage : MonoBehaviour
{
    void Start()
    {
        Caculatestarge myCaculate = new Caculatestarge();
         //个人月收入两万
        PersonStrage tmpPerson = new PersonStrage(20000);
        myCaculate.Caculatestage(tmpPerson);
         //企业月收入两万
        CompananyStrage tmpCompaney = new CompananyStrage(20000);
        myCaculate.Caculatestage(tmpCompaney);
    }
}
  • 计算结果
Licensed under CC BY-NC-SA 4.0
0