策略模式(Strategy Pattern):定义一系列算法类,将每一个算法封装起来,并让它们可以相互替换,策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。
模式角色与结构:
示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace CSharp.DesignPattern.StrategyPattern {class Program{static void Main(string[] args){MovieTicket mt = new MovieTicket();double originalPrice = 60.0;double currentPrice;mt.Price = originalPrice;IDiscount discount = new StudentDiscount(); // 也可以用配置文件和反射创建新的对象mt.Discount = discount; // 注入折扣对象 currentPrice = mt.GetCurrentPrice();Console.Write("student price: " + currentPrice.ToString());}}// 环境类class MovieTicket{public double GetCurrentPrice(){return _discount.calculate(this._price);}public double Price{get { return _price; }set { _price = value; }}public IDiscount Discount{set { _discount = value; }}private double _price;private IDiscount _discount; // 维持一个对抽象策略类的引用 }// 抽象策略类 interface IDiscount{double calculate(double price);}// 具体策略类class StudentDiscount : IDiscount{public double calculate(double price){return price * 0.8;}}// 具体策略类class ChildrenDiscount : IDiscount{public double calculate(double price){return price - 10;}}// 具体策略类class VIPDiscount : IDiscount{public double calculate(double price){return price * 0.5;}} }