工厂模式中只管生产实例,具体怎么使用工厂实例由调用方决定,工厂模式调用方可以直接调用工厂实例的方法属性等。
策略模式是将生成实例的使用策略放在策略类中配置后才提供调用方使用,策略模式不能直接调用实例的方法属性,需要在策略类中封装策略后调用。
事列代码:
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();