1. 程式人生 > >策略模式

策略模式

new () nal line esp strategy 0.12 cal div

namespace StrategyPattern
{
    // 所得稅計算策略
    public interface ITaxStragety
    {
        double CalculateTax(double income);
    }

    // 個人所得稅
    public class PersonalTaxStrategy : ITaxStragety
    {
        public double CalculateTax(double income)
        {
            return income * 0.12;
        }
    }

    
// 企業所得稅 public class EnterpriseTaxStrategy : ITaxStragety { public double CalculateTax(double income) { return (income - 3500) > 0 ? (income - 3500) * 0.045 : 0.0; } } public class InterestOperation { private ITaxStragety m_strategy;
public InterestOperation(ITaxStragety strategy) { this.m_strategy = strategy; } public double GetTax(double income) { return m_strategy.CalculateTax(income); } } class App { static void Main(string[] args) {
// 個人所得稅方式 InterestOperation operation = new InterestOperation(new PersonalTaxStrategy()); Console.WriteLine("個人支付的稅為:{0}", operation.GetTax(5000.00)); // 企業所得稅 operation = new InterestOperation(new EnterpriseTaxStrategy()); Console.WriteLine("企業支付的稅為:{0}", operation.GetTax(50000.00)); Console.Read(); } } }

用來替換if else

策略模式