CSharp设计模式读书笔记(22):策略模式(学习难度:★☆☆☆☆,使用频率:★★★★☆)...
生活随笔
收集整理的這篇文章主要介紹了
CSharp设计模式读书笔记(22):策略模式(学习难度:★☆☆☆☆,使用频率:★★★★☆)...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
策略模式(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
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的CSharp设计模式读书笔记(22):策略模式(学习难度:★☆☆☆☆,使用频率:★★★★☆)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到屎和很多苍蝇是怎么回事
- 下一篇: 梦到了死人什么意思