当前位置: 首页 > 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…...

安装OpenClaw时,为什么需要先安装Node.js?不装行不行?

## 为什么OpenClaw需要Node.js&#xff1f;不装行不行&#xff1f; 最近在折腾OpenClaw这个工具的时候&#xff0c;发现它的安装文档里第一步就是要求安装Node.js。很多刚接触的朋友可能会纳闷——这俩东西看起来八竿子打不着&#xff0c;为什么非得先装Node.js&#xff1f;不装…...

景区服务碎片化投诉多?巨有科技补齐智慧服务短板

当下文旅行业持续回暖&#xff0c;景区客流稳步回升&#xff0c;但服务端的老难题却始终制约着运营口碑与长期发展。不少景区深陷人工服务不足、流程碎片化的困境&#xff0c;游客咨询无响应、游览指引不清晰、售后反馈无渠道&#xff0c;投诉率居高不下&#xff0c;即便投入人…...

SAP UI5中DOMParser解析XML关键步骤

SAP UI5框架中基于DOMParser的XML数据解析机制涉及多个关键环节&#xff0c;这些步骤共同构成了元数据解析的核心流程。根据技术文档分析&#xff0c;其关键实现步骤如下&#xff1a; 1. 解析器实例化与初始化 var xmlParse function (text) {/// <summary>Returns an…...

CICFlowmeter深度解析:80+维流量特征的含义与应用场景

CICFlowmeter深度解析&#xff1a;80维流量特征的含义与应用场景 在当今这个数据驱动的时代&#xff0c;网络流量早已不再是简单的字节流&#xff0c;而是承载着业务逻辑、用户行为乃至安全威胁的复杂信号。对于安全研究员、网络性能优化专家以及任何需要洞察网络内部运作的专业…...

eslint_d.js vs 原生ESLint:实测对比,谁才是前端开发的效率神器?

eslint_d.js vs 原生ESLint&#xff1a;实测对比&#xff0c;谁才是前端开发的效率神器&#xff1f; 【免费下载链接】eslint_d.js Makes eslint the fastest linter on the planet 项目地址: https://gitcode.com/gh_mirrors/es/eslint_d.js 在现代前端开发中&#xff…...

flux2-kustomize-helm-example完全指南:从入门到精通的GitOps多环境部署方案

flux2-kustomize-helm-example完全指南&#xff1a;从入门到精通的GitOps多环境部署方案 【免费下载链接】flux2-kustomize-helm-example A GitOps workflow example for multi-env deployments with Flux, Kustomize and Helm. 项目地址: https://gitcode.com/gh_mirrors/fl…...

Arnis实战手册:5个关键配置技巧打造完美Minecraft城市

Arnis实战手册&#xff1a;5个关键配置技巧打造完美Minecraft城市 【免费下载链接】arnis Arnis - Generate cities from real life in Minecraft using Python 项目地址: https://gitcode.com/GitHub_Trending/ar/arnis Arnis是一款能够将现实世界城市数据转化为Minecr…...

2.Vue编写一个app

1.src中重要的组成 1.1main.ts // 引入createApp用于创建应用 import { createApp } from "vue"; // 引用App根组件 import App from ./App.vue;createApp(App).mount(#app)1.2 App.vue 其中要写三种标签 <template> <!--html--> </template>…...

【SQL学习笔记1】增删改查+多表连接全解析(内附SQL免费在线练习工具)

可以使用Sqliteviz这个网站免费编写sql语句&#xff0c;它能够让用户直接在浏览器内练习SQL的语法&#xff0c;不需要安装任何软件。 链接如下&#xff1a; sqliteviz 注意&#xff1a; 在转写SQL语法时&#xff0c;关键字之间有一个特定的顺序&#xff0c;这个顺序会影响到…...

【HTML-16】深入理解HTML中的块元素与行内元素

HTML元素根据其显示特性可以分为两大类&#xff1a;块元素(Block-level Elements)和行内元素(Inline Elements)。理解这两者的区别对于构建良好的网页布局至关重要。本文将全面解析这两种元素的特性、区别以及实际应用场景。 1. 块元素(Block-level Elements) 1.1 基本特性 …...