当前位置: 首页 > news >正文

C#设计模式--策略模式(Strategy Pattern)

策略模式是一种行为设计模式,它使你能在运行时改变对象的行为。在策略模式定义了一系列算法或策略,并将每个算法封装在独立的类中,使得它们可以互相替换。通过使用策略模式,可以在运行时根据需要选择不同的算法,而不需要修改客户端代码。

主要解决的问题

解决在多种相似算法存在时,使用条件语句(如if…else)导致的复杂性和难以维护的问题。

1. 定义策略接口

public interface IStrategy
{void Execute();
}

2. 实现具体策略

public class ConcreteStrategyA : IStrategy
{public void Execute(){Console.WriteLine("Executing strategy A");}
}public class ConcreteStrategyB : IStrategy
{public void Execute(){Console.WriteLine("Executing strategy B");}
}

3. 上下文类

public class Context
{private IStrategy _strategy;public Context(IStrategy strategy){_strategy = strategy;}public void SetStrategy(IStrategy strategy){_strategy = strategy;}public void ExecuteStrategy(){_strategy.Execute();}
}

类图

IStrategy
+void Execute()
ConcreteStrategyA
+void Execute()
ConcreteStrategyB
+void Execute()
Context
-IStrategy _strategy
+Context(IStrategy strategy)
+void SetStrategy(IStrategy strategy)
+void ExecuteStrategy()

用途

策略模式主要用于以下场景:
• 算法变化:当一个类的行为或其算法需要在运行时动态改变时。
• 多个算法变体:当有多个算法变体,并且需要在运行时选择其中一个时。
• 解耦:将算法的定义与使用算法的客户端解耦。

优点

  1. 灵活性:可以在运行时动态切换算法。
  2. 扩展性:增加新的策略非常容易,只需实现策略接口即可。
  3. 解耦:策略类和上下文类之间松耦合,符合开闭原则。

缺点

  1. 客户端复杂度:客户端必须了解所有策略类的区别,以便选择合适的策略。
  2. 增加对象数量:每个策略都是一个类,可能会导致类的数量增加。

实际开发中的应用举例

示例1:订单处理系统中的促销策略

假设一个订单处理系统,需要根据不同的促销策略,比如:没折扣、打折扣。也可以用是会员积分兑换,来计算订单的最终价格。

1. 定义促销策略接口

public interface IPromotionStrategy
{decimal ApplyPromotion(decimal originalPrice);
}

2. 实现具体的促销策略

public class NoDiscountStrategy : IPromotionStrategy
{public decimal ApplyPromotion(decimal originalPrice){return originalPrice; // 没有折扣}
}public class PercentageDiscountStrategy : IPromotionStrategy
{private readonly decimal _discountPercentage;public PercentageDiscountStrategy(decimal discountPercentage){_discountPercentage = discountPercentage;}public decimal ApplyPromotion(decimal originalPrice){return originalPrice * (1 - _discountPercentage / 100);//折扣}
}public class FixedAmountDiscountStrategy : IPromotionStrategy
{private readonly decimal _discountAmount;public FixedAmountDiscountStrategy(decimal discountAmount){_discountAmount = discountAmount;}public decimal ApplyPromotion(decimal originalPrice){return originalPrice - _discountAmount;}
}

3. 上下文类

public class Order
{private IPromotionStrategy _promotionStrategy;private decimal _originalPrice;public Order(decimal originalPrice, IPromotionStrategy promotionStrategy){_originalPrice = originalPrice;_promotionStrategy = promotionStrategy;}public void SetPromotionStrategy(IPromotionStrategy promotionStrategy){_promotionStrategy = promotionStrategy;}public decimal CalculateFinalPrice(){return _promotionStrategy.ApplyPromotion(_originalPrice);}
}

4. 使用示例

class Program
{static void Main(string[] args){// 创建订单,初始价格为100元,没有折扣var order = new Order(100, new NoDiscountStrategy());Console.WriteLine($"Original price: {order.CalculateFinalPrice()}");// 应用百分比折扣策略,折扣10%order.SetPromotionStrategy(new PercentageDiscountStrategy(10));Console.WriteLine($"Price after 10% discount: {order.CalculateFinalPrice()}");// 应用固定金额折扣策略,折扣20元order.SetPromotionStrategy(new FixedAmountDiscountStrategy(20));Console.WriteLine($"Price after fixed 20 discount: {order.CalculateFinalPrice()}");}
}

类图:

IPromotionStrategy
+decimal ApplyPromotion(decimal originalPrice)
NoDiscountStrategy
+decimal ApplyPromotion(decimal originalPrice)
PercentageDiscountStrategy
-decimal _discountPercentage
+PercentageDiscountStrategy(decimal discountPercentage)
+decimal ApplyPromotion(decimal originalPrice)
FixedAmountDiscountStrategy
-decimal _discountAmount
+FixedAmountDiscountStrategy(decimal discountAmount)
+decimal ApplyPromotion(decimal originalPrice)
Order
-IPromotionStrategy _promotionStrategy
-decimal _originalPrice
+Order(decimal originalPrice, IPromotionStrategy promotionStrategy)
+void SetPromotionStrategy(IPromotionStrategy promotionStrategy)
+decimal CalculateFinalPrice()

解释

  1. 定义促销策略接口:IPromotionStrategy 接口定义了一个 ApplyPromotion 方法,用于计算应用促销后的价格。
  2. 实现具体的促销策略:
    • NoDiscountStrategy:不应用任何折扣。
    • PercentageDiscountStrategy:应用百分比折扣。
    • FixedAmountDiscountStrategy:应用固定金额折扣。
  3. 上下文类:Order 类包含一个促销策略,并提供方法来设置促销策略和计算最终价格。
  4. 使用示例:创建一个订单,初始价格为100元,然后依次应用不同的促销策略,输出最终价格。

示例2:物流管理系统中的运输策略

假设一个物流管理系统,需要根据不同的运输方式(如快递、货运、空运等)来计算运费。也可以使用策略模式来实现这一点。

1. 定义运输策略接口

public interface ITransportStrategy
{decimal CalculateShippingCost(decimal weight, decimal distance);
}

2. 实现具体的运输策略

public class ExpressShippingStrategy : ITransportStrategy
{public decimal CalculateShippingCost(decimal weight, decimal distance){// 快递费用计算公式:重量 * 距离 * 0.5return weight * distance * 0.5m;}
}public class FreightShippingStrategy : ITransportStrategy
{public decimal CalculateShippingCost(decimal weight, decimal distance){// 货运费用计算公式:重量 * 距离 * 0.3return weight * distance * 0.3m;}
}public class AirShippingStrategy : ITransportStrategy
{public decimal CalculateShippingCost(decimal weight, decimal distance){// 空运费用计算公式:重量 * 距离 * 1.0return weight * distance * 1.0m;}
}

3. 上下文类

public class Shipment
{private ITransportStrategy _transportStrategy;private decimal _weight;private decimal _distance;public Shipment(decimal weight, decimal distance, ITransportStrategy transportStrategy){_weight = weight;_distance = distance;_transportStrategy = transportStrategy;}public void SetTransportStrategy(ITransportStrategy transportStrategy){_transportStrategy = transportStrategy;}public decimal CalculateTotalCost(){return _transportStrategy.CalculateShippingCost(_weight, _distance);}
}

4. 使用示例

class Program
{static void Main(string[] args){// 创建一个货物,重量为100公斤,距离为500公里,使用快递运输var shipment = new Shipment(100, 500, new ExpressShippingStrategy());Console.WriteLine($"Express Shipping Cost: {shipment.CalculateTotalCost()}");// 更改为货运运输shipment.SetTransportStrategy(new FreightShippingStrategy());Console.WriteLine($"Freight Shipping Cost: {shipment.CalculateTotalCost()}");// 更改为空运运输shipment.SetTransportStrategy(new AirShippingStrategy());Console.WriteLine($"Air Shipping Cost: {shipment.CalculateTotalCost()}");}
}

类图:

ITransportStrategy
+decimal CalculateShippingCost(decimal weight, decimal distance)
ExpressShippingStrategy
+decimal CalculateShippingCost(decimal weight, decimal distance)
FreightShippingStrategy
+decimal CalculateShippingCost(decimal weight, decimal distance)
AirShippingStrategy
+decimal CalculateShippingCost(decimal weight, decimal distance)
Shipment
-ITransportStrategy _transportStrategy
-decimal _weight
-decimal _distance
+Shipment(decimal weight, decimal distance, ITransportStrategy transportStrategy)
+void SetTransportStrategy(ITransportStrategy transportStrategy)
+decimal CalculateTotalCost()

解释

  1. 定义运输策略接口:ITransportStrategy 接口定义了一个 CalculateShippingCost 方法,用于计算运输费用。
  2. 实现具体的运输策略:
    • ExpressShippingStrategy:快递运输费用计算。
    • FreightShippingStrategy:货运运输费用计算。
    • AirShippingStrategy:空运运输费用计算。
  3. 上下文类:Shipment 类包含一个运输策略,并提供方法来设置运输策略和计算总费用。
  4. 使用示例:创建一个货物,初始运输方式为快递,然后依次更改为货运和空运,输出每种运输方式的费用。

优点

  1. 灵活性:可以在运行时动态切换促销策略。
  2. 扩展性:增加新的促销策略非常容易,只需实现 IPromotionStrategy 接口即可。
  3. 解耦:订单类和促销策略类之间松耦合,符合开闭原则。

缺点

  1. 客户端复杂度:客户端必须了解所有促销策略的区别,以便选择合适的策略。
  2. 增加对象数量:每个促销策略都是一个类,可能会导致类的数量增加。

相关文章:

C#设计模式--策略模式(Strategy Pattern)

策略模式是一种行为设计模式,它使你能在运行时改变对象的行为。在策略模式定义了一系列算法或策略,并将每个算法封装在独立的类中,使得它们可以互相替换。通过使用策略模式,可以在运行时根据需要选择不同的算法,而不需…...

【opencv入门教程】15. 访问像素的十四种方式

文章选自: 一、像素访问 一张图片由许多个点组成,每个点就是一个像素,每个像素包含不同的值,对图像像素操作是图像处理过程中常使用的 二、访问像素 void Samples::AccessPixels1(Mat &image, int div 64) {int nl imag…...

【MySQL调优】如何进行MySQL调优?从参数、数据建模、索引、SQL语句等方向,三万字详细解读MySQL的性能优化方案(2024版)

导航: 本文一些内容需要聚簇索引、非聚簇索引、B树、覆盖索引、索引下推等前置概念,虽然本文有简单回顾,但详细可以参考下文的【MySQL高级篇】 【Java笔记踩坑汇总】Java基础JavaWebSSMSpringBootSpringCloud瑞吉外卖/谷粒商城/学成在线设计模…...

根据html的段落长度设置QtextBrowser的显示内容,最少显示一个段落

要根据 HTML 段落的长度设置 QTextBrowser 的显示内容,并确保至少显示一个段落,可以通过以下步骤来实现: 加载 HTML 内容:首先,你需要加载 HTML 内容到 QTextBrowser 中。可以通过 setHtml() 方法来设置 HTML。 计算段…...

基于Huffman编码的GPS定位数据无损压缩算法

目录 一、引言 二、霍夫曼编码 三、经典Huffman编码 四、适应性Huffman编码 五、GPS定位数据压缩 提示:文末附定位数据压缩工具和源码 一、引言 车载监控系统中,车载终端需要获取GPS信号(经度、纬 度、速度、方向等)实时上传…...

php:完整部署Grid++Report到php项目,并实现模板打印

一、下载Grid++Report软件 路径:开发者安装包下载 - 锐浪报表工具 二、 安装软件 1、对下载的压缩包运行内部的exe文件 2、选择语言 3、 完成安装引导 下一步即可 4、接收许可协议 点击“我接受” 5、选择安装路径 “浏览”选择安装路径,点击"安装" 6、完成…...

C标签和 EL表达式的在前端界面的应用

目录 前言 常用的c标签有: for循环 1 表示 普通的for循环的 2 常在集合中使用 表示 选择关系 1 简单的表示如果 2 表示如果。。否则。。 EL表达式 格式 : ${属性名/对象/ 集合} 前言 本篇博客介绍 c标签和el表达式的使用 使用C标签 要引入 …...

Linux絮絮叨(四) 系统目录结构

Linux 系统的目录结构(Filesystem Hierarchy Standard, FHS)定义了 Linux 系统中文件系统的标准布局,以下是一些常见目录的功能: 根目录 / 描述:所有文件和目录的起始点,Linux 文件系统的根。内容&#xf…...

Java基于SpringBoot的网上订餐系统,附源码

博主介绍:✌Java老徐、7年大厂程序员经历。全网粉丝12w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ 🍅文末获取源码联系🍅 👇🏻 精彩专栏推荐订阅👇&…...

《Java核心技术I》死锁

死锁 账户1:200元账户2: 300元线程1:从账号1转300到账户2线程2:从账户2转400到账户1 如上,线程1和线程2显然都被阻塞,两个账户的余额都不足以转账,两个线程都无法执行下去。 有可能会因为每一个线程要等…...

【Windows11系统局域网共享文件数据】

【Windows11系统局域网共享文件数据】 1. 引言1. 规划网络2. 获取必要的硬件3. 设置网络4. 配置网络设备5. 测试网络连接6. 安全性和维护7. 扩展和优化 2. 准备工作2.1: 启用网络发现和文件共享2.2: 设置共享文件夹 3. 访问共享文件夹4. 小贴士5. 总结 1. 引言 随着家庭和小型办…...

MCU、ARM体系结构,单片机基础,单片机操作

计算机基础 计算机的组成 输入设备、输出设备、存储器、运算器、控制器 输入设备:将其他信号转换为计算机可以识别的信号(电信号)。输出设备:将电信号(0、1)转为人或其他设备能理解的…...

在办公室环境中用HMD替代传统显示器的优势

VR头戴式显示器(HMD)是进入虚拟现实环境的一把钥匙,拥有HMD的您将能够在虚拟现实世界中尽情探索未知领域,正如如今的互联网一样,虚拟现实环境能够为您提供现实中无法实现的或不可能实现的事。随着技术的不断进步&#…...

ssm 多数据源 注解版本

application.xml 配置如下 <!-- 使用 DruidDataSource 数据源 --><bean id"primaryDataSource" class"com.alibaba.druid.pool.DruidDataSource" init-method"init" destroy-method"close"></bean> <!-- 使用 数…...

selenium常见接口函数使用

博客主页&#xff1a;花果山~程序猿-CSDN博客 文章分栏&#xff1a;测试_花果山~程序猿的博客-CSDN博客 关注我一起学习&#xff0c;一起进步&#xff0c;一起探索编程的无限可能吧&#xff01;让我们一起努力&#xff0c;一起成长&#xff01; 目录 1. 查找 查找方式 css_s…...

STM32F103单片机使用STM32CubeMX新建IAR工程步骤

打开STM32CubeMX软件&#xff0c;选择File 选择新建工程 在打开的窗口输入单片机型号 在右下角选择单片机型号&#xff0c;然后点右上角 start project&#xff0c;开始新建工程。 接下来设置调试接口&#xff0c;在左边System Core中选择 SYS&#xff0c;然后在右右边debu…...

刷题重开:找出字符串中第一个匹配项的下标——解题思路记录

问题描述&#xff1a; 给你两个字符串 haystack 和 needle &#xff0c;请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标&#xff08;下标从 0 开始&#xff09;。如果 needle 不是 haystack 的一部分&#xff0c;则返回 -1 。 示例 1&#xff1a; 输入&…...

product/admin/list?page=0size=10field=jancodevalue=4562249292272

文章目录 1、ProductController2、AdminCommonService3、ProductApiService4、ProductCommonService5、ProductSqlService https://api.crossbiog.com/product/admin/list?page0&size10&fieldjancode&value45622492922721、ProductController GetMapping("ad…...

人工智能机器学习无监督学习概念及应用详解

无监督学习&#xff1a;深入解析 引言 在人工智能和机器学习的领域中&#xff0c;无监督学习&#xff08;Unsupervised Learning&#xff09;是一种重要的学习范式。与监督学习不同&#xff0c;无监督学习不依赖于标签数据&#xff0c;而是通过模型从无标签的数据中学习数据的…...

APM装机教程(五):测绘无人船

文章目录 前言一、元生惯导RTK使用二、元厚HXF260测深仪使用三、云卓H2pro遥控器四、海康威视摄像头 前言 船体&#xff1a;超维USV-M1000 飞控&#xff1a;pix6c mini 测深仪&#xff1a;元厚HXF160 RTK&#xff1a;元生惯导RTK 遥控器&#xff1a;云卓H12pro 摄像头&#xf…...

7.4.分块查找

一.分块查找的算法思想&#xff1a; 1.实例&#xff1a; 以上述图片的顺序表为例&#xff0c; 该顺序表的数据元素从整体来看是乱序的&#xff0c;但如果把这些数据元素分成一块一块的小区间&#xff0c; 第一个区间[0,1]索引上的数据元素都是小于等于10的&#xff0c; 第二…...

基于uniapp+WebSocket实现聊天对话、消息监听、消息推送、聊天室等功能,多端兼容

基于 ​UniApp + WebSocket​实现多端兼容的实时通讯系统,涵盖WebSocket连接建立、消息收发机制、多端兼容性配置、消息实时监听等功能,适配​微信小程序、H5、Android、iOS等终端 目录 技术选型分析WebSocket协议优势UniApp跨平台特性WebSocket 基础实现连接管理消息收发连接…...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...

自然语言处理——Transformer

自然语言处理——Transformer 自注意力机制多头注意力机制Transformer 虽然循环神经网络可以对具有序列特性的数据非常有效&#xff0c;它能挖掘数据中的时序信息以及语义信息&#xff0c;但是它有一个很大的缺陷——很难并行化。 我们可以考虑用CNN来替代RNN&#xff0c;但是…...

CRMEB 框架中 PHP 上传扩展开发:涵盖本地上传及阿里云 OSS、腾讯云 COS、七牛云

目前已有本地上传、阿里云OSS上传、腾讯云COS上传、七牛云上传扩展 扩展入口文件 文件目录 crmeb\services\upload\Upload.php namespace crmeb\services\upload;use crmeb\basic\BaseManager; use think\facade\Config;/*** Class Upload* package crmeb\services\upload* …...

SAP学习笔记 - 开发26 - 前端Fiori开发 OData V2 和 V4 的差异 (Deepseek整理)

上一章用到了V2 的概念&#xff0c;其实 Fiori当中还有 V4&#xff0c;咱们这一章来总结一下 V2 和 V4。 SAP学习笔记 - 开发25 - 前端Fiori开发 Remote OData Service(使用远端Odata服务)&#xff0c;代理中间件&#xff08;ui5-middleware-simpleproxy&#xff09;-CSDN博客…...

基于Java+MySQL实现(GUI)客户管理系统

客户资料管理系统的设计与实现 第一章 需求分析 1.1 需求总体介绍 本项目为了方便维护客户信息为了方便维护客户信息&#xff0c;对客户进行统一管理&#xff0c;可以把所有客户信息录入系统&#xff0c;进行维护和统计功能。可通过文件的方式保存相关录入数据&#xff0c;对…...

人机融合智能 | “人智交互”跨学科新领域

本文系统地提出基于“以人为中心AI(HCAI)”理念的人-人工智能交互(人智交互)这一跨学科新领域及框架,定义人智交互领域的理念、基本理论和关键问题、方法、开发流程和参与团队等,阐述提出人智交互新领域的意义。然后,提出人智交互研究的三种新范式取向以及它们的意义。最后,总结…...

OD 算法题 B卷【正整数到Excel编号之间的转换】

文章目录 正整数到Excel编号之间的转换 正整数到Excel编号之间的转换 excel的列编号是这样的&#xff1a;a b c … z aa ab ac… az ba bb bc…yz za zb zc …zz aaa aab aac…; 分别代表以下的编号1 2 3 … 26 27 28 29… 52 53 54 55… 676 677 678 679 … 702 703 704 705;…...

离线语音识别方案分析

随着人工智能技术的不断发展&#xff0c;语音识别技术也得到了广泛的应用&#xff0c;从智能家居到车载系统&#xff0c;语音识别正在改变我们与设备的交互方式。尤其是离线语音识别&#xff0c;由于其在没有网络连接的情况下仍然能提供稳定、准确的语音处理能力&#xff0c;广…...