商丘网站制作方案,网络课程设计开发,网络营销公司怎么赚钱的,网站怎么做404 301策略模式(Strategy Pattern)#xff1a;定义一系列算法类#xff0c;将每一个算法封装起来#xff0c;并让它们可以相互替换#xff0c;策略模式让算法独立于使用它的客户而变化#xff0c;也称为政策模式(Policy)。 模式角色与结构#xff1a; 示例代码#xff1a; usi…策略模式(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;}}
} 转载于:https://www.cnblogs.com/thlzhf/p/3993799.html