文章出處

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


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()