标签:sign targe ext inter void 决定 怎么 color person
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp6 { /// <summary> /// 策略模式(个人所得税例子) /// </summary> 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); } } // 所得税计算策略 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; } } }
调用:
// 个人所得税方式 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));
策略模式与简单工厂对比
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp6 { /// <summary> /// 简单工厂 /// </summary> public class PeopleFactory { public People getPeople(string name) { if (name.Equals("Xiaoming")) { return new Xiaoming(); } else if (name.Equals("Xiaohong")) { return new Xiaohong(); } return null; } } public class Xiaoming : People { public void Eat() { Console.WriteLine("小明吃饭"); } public void run() { Console.WriteLine("小明跑步"); } public void wear() { Console.WriteLine("小明穿衣"); } } public class Xiaohong : People { public void Eat() { Console.WriteLine("小红吃饭"); } public void run() { Console.WriteLine("小红跑步"); } public void wear() { Console.WriteLine("小红穿衣"); } } public interface People { void Eat(); void run(); void wear(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp6 { /// <summary> /// 策略模式 /// </summary> public class StrategySign { private People people; public StrategySign(People people) { this.people = people; } public StrategySign(string name) { if (name.Equals("Xiaoming")) { this.people = new Xiaoming(); } else if (name.Equals("Xiaohong")) { this.people = new Xiaohong(); } } public void run() { people.Eat(); people.run(); people.wear(); } } }
调用:
//简单工厂 PeopleFactory peopleFactory = new PeopleFactory(); People people = peopleFactory.getPeople("Xiaohong"); people.Eat(); //策略模式 StrategySign strategySign = new StrategySign("Xiaohong"); strategySign.run(); Console.Read();
标签:sign targe ext inter void 决定 怎么 color person
原文地址:https://www.cnblogs.com/macT/p/13231147.html