设计模式:策略模式示例

文章目录

      • 示例 1: 排序策略
      • 示例 2: 支付策略
      • 示例 3: 压缩策略

策略模式的示例非常多样,下面是一些场景的示例及其代码实现:

示例 1: 排序策略

在需要对不同类型的数据集进行排序时,可以使用策略模式来选择不同的排序算法。

// 策略接口
public interface SortingStrategy {<T extends Comparable<T>> void sort(List<T> items);
}// 具体策略类:快速排序
public class QuickSortStrategy implements SortingStrategy {public <T extends Comparable<T>> void sort(List<T> items) {// 实现快速排序逻辑System.out.println("QuickSort strategy is used.");}
}// 具体策略类:冒泡排序
public class BubbleSortStrategy implements SortingStrategy {public <T extends Comparable<T>> void sort(List<T> items) {// 实现冒泡排序逻辑System.out.println("BubbleSort strategy is used.");}
}// 上下文
public class SortedList {private SortingStrategy strategy;public void setSortingStrategy(SortingStrategy strategy) {this.strategy = strategy;}public <T extends Comparable<T>> void sort(List<T> items) {strategy.sort(items);}
}// 客户端代码
public class StrategyPatternExample {public static void main(String[] args) {SortedList list = new SortedList();list.setSortingStrategy(new QuickSortStrategy());list.sort(new ArrayList<>(Arrays.asList(5, 3, 2, 4, 1)));list.setSortingStrategy(new BubbleSortStrategy());list.sort(new ArrayList<>(Arrays.asList(5, 3, 2, 4, 1)));}
}

示例 2: 支付策略

电子商务应用程序中,可以根据用户的支付方式选择不同的支付策略。

// 策略接口
public interface PaymentStrategy {void pay(int amount);
}// 具体策略类:信用卡支付
public class CreditCardPayment implements PaymentStrategy {private String cardNumber;public CreditCardPayment(String cardNumber) {this.cardNumber = cardNumber;}public void pay(int amount) {System.out.println(amount + " paid with credit card.");}
}// 具体策略类:PayPal支付
public class PayPalPayment implements PaymentStrategy {private String emailId;public PayPalPayment(String email) {this.emailId = email;}public void pay(int amount) {System.out.println(amount + " paid using PayPal.");}
}// 上下文
public class ShoppingCart {private PaymentStrategy paymentStrategy;public void setPaymentStrategy(PaymentStrategy paymentStrategy) {this.paymentStrategy = paymentStrategy;}public void checkout(int amount) {paymentStrategy.pay(amount);}
}// 客户端代码
public class StrategyPatternExample {public static void main(String[] args) {ShoppingCart cart = new ShoppingCart();cart.setPaymentStrategy(new CreditCardPayment("1234567890123456"));cart.checkout(100);cart.setPaymentStrategy(new PayPalPayment("myemail@example.com"));cart.checkout(200);}
}

示例 3: 压缩策略

在需要压缩文件的应用程序中,可以根据文件类型或用户的选择应用不同的压缩策略。

// 策略接口
public interface CompressionStrategy {void compressFiles(List<File> files);
}// 具体策略类:ZIP压缩
public class ZipCompressionStrategy implements CompressionStrategy {public void compressFiles(List<File> files) {// 使用ZIP压缩System.out.println("Using ZIP compression strategy.");}
}// 具体策略类:RAR压缩
public class RarCompressionStrategy implements CompressionStrategy {public void compressFiles(List<File> files) {// 使用RAR压缩System.out.println("Using RAR compression strategy.");}
}// 上下文
public class CompressionContext {private CompressionStrategy strategy;public void setCompressionStrategy(CompressionStrategy strategy) {this.strategy = strategy;}public void createArchive(List<File> files) {strategy.compressFiles(files);}
}// 客户端代码
public class StrategyPatternExample {public static void main(String[] args) {CompressionContext ctx = new CompressionContext();ctx.setCompressionStrategy(new ZipCompressionStrategy());ctx.createArchive(Collections.singletonList(new File("file1.txt")));ctx.setCompressionStrategy(new RarCompressionStrategy());ctx.createArchive(Collections.singletonList(new File("file2.txt")));}
}

这些示例展示了策略模式在不同场景下的应用。策略模式允许在运行时选择合适的算法或行为,同时也方便未来添加新的策略而不影响现有代码。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/797993.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

libVLC 音频输出设备切换

libvlc_audio_output_list_get和libvlc_audio_output_device_list_get是libVLC 库中用于处理音频输出的两个函数。 libvlc_audio_output_list_get函数用于获取可用的音频输出模块列表。这个列表通常包括不同的音频输出方式&#xff0c;例如 Pulseaudio、ALSA 等。通过这个函数…

Linux——用户管理,文件压缩命令

用户管理命令 (1)系统存储用户信息的位置: /etc/passwd:存储用户的基本信息 UID:用户ID GID:组ID; (2)系统存储组信息的位置: /etc/group (3)系统存储用户密码信息的位置: /etc/shadow (2)添加用户 使用命令添加新用户:useradd newname 桌面添加:右键:设置:用户,解锁,添加用…

算法第三十九天-验证二叉树的前序序列化

验证二叉树的前序序列化 题目要求 解题思路 方法一&#xff1a;栈 栈的思路是「自底向上」的想法。下面要结合本题是「前序遍历」这个重要特点。 我们知道「前序遍历」是按照「根节点-左子树-右子树」的顺序遍历的&#xff0c;只有当根节点的所有左子树遍历完成之后&#xf…

排查Java中的OOM(Out of Memory)问题

Java的OOM&#xff08;OutOfMemoryError&#xff09;问题通常表示Java虚拟机&#xff08;JVM&#xff09;在尝试分配内存给对象时&#xff0c;无法找到足够的连续内存空间。这可能是由于内存泄漏、堆内存不足或其他原因导致的。排查OOM问题通常涉及以下几个步骤&#xff1a; 查…

使用 Docker 部署 Photopea 在线 PS 工具

1&#xff09;Photopea 介绍 GitHub&#xff1a;https://github.com/photopea/photopea 官方手册&#xff1a;https://www.photopea.com/learn/ Adobe 出品的「PhotoShop」想必大家都很熟悉啦&#xff0c;但是「PhotoShop」现在对电脑配置要求越来越高&#xff0c;体积越来越大…

逆向入门:为ctf国赛而写的笔记 day01

目录 通用寄存器&#xff1a; EAX:累加寄存器&#xff0c;是很多加法乘法指令的缺省寄存器 EBX&#xff1a;基地址寄存器&#xff0c;在内存寻址时存放基地址 ECX&#xff1a;计数器 EDX&#xff1a;数据寄存器&#xff0c;被用于来放整数除法产生的余数 变址寄存器 标志…

流行的API架构学习

几种流行的API架构风格图 SOAP&#xff08;Simple Object Access Protocol&#xff09; 优点&#xff1a;SOAP 是一种基于 XML 的通信协议&#xff0c;具有良好的跨平台和跨语言支持。它提供了丰富的安全性和事务管理功能&#xff0c;并支持复杂的消息交换模式。 缺点&#xf…

windows,web端网页唤起打开本地的客户端程序

这里写自定义目录标题 需求&#xff1a;在电脑浏览器网页唤起本地的应用程序 使用类似以下代码 <a href"myprotocol:">打开飞书</a>在客户端安装的时候在注册表会有自己的协议&#xff0c;若是没有的可自定义注册表 自定义注册表步骤 1.winr 运行 regedi…

物联网工程-系统设计作业

1.设计一套基于RFID牛场养殖信息管理系统&#xff0c;并给出系统设计思路、系统构架和控制流程图。 一、设计思想 为方便牛场养殖员鉴别和管理牛群&#xff0c;为每只牛佩戴有RFID标签的动物耳钉&#xff0c;并将牛的健康情况录入数据库中&#xff0c;随着牛的生长&#xff0c;…

关于递归和回溯的思考

完整代码: 力扣112路径总和 class Solution { private:bool traversal(TreeNode* cur, int count) {if (!cur->left && !cur->right && count 0) return true; // 遇到叶子节点&#xff0c;并且计数为0if (!cur->left && !cur->right) r…

[StartingPoint][Tier1]Funnel

Task 1 How many TCP ports are open? (打开了多少个 TCP 端口&#xff1f;) # nmap -sS -T4 10.129.224.226 --min-rate 1000 2 Task 2 What is the name of the directory that is available on the FTP server? (FTP 服务器上可用的目录名称是什么&#xff1f;) $ n…

数据库系统概论(超详解!!!)第三节 关系数据库标准语言SQL(Ⅵ)

1.空值的处理 空值就是“不知道”或“不存在”或“无意义”的值。 一般有以下几种情况&#xff1a; 该属性应该有一个值&#xff0c;但目前不知道它的具体值 &#xff1b;该属性不应该有值 &#xff1b;由于某种原因不便于填写。 1.空值的产生 空值是一个很特殊的值&#x…

云仓酒庄旗下雷盛红酒入驻香港星怡SingLa餐厅共绘美食美酒新篇章

近日&#xff0c;云仓酒庄旗下品牌雷盛红酒正式入驻香港餐厅星怡SingLa&#xff0c;这一跨界合作不仅为香港市民和游客带来了全新的味蕾享受&#xff0c;也标志着美食与美酒文化的很好结合&#xff0c;共同绘就了一幅精彩绝伦的美食美酒新篇章。 云仓酒庄一直以来都致力于为消费…

Rust 程序设计语言学习——枚举模式匹配

枚举&#xff08;enumerations&#xff09;&#xff0c;也被称作 enums。match 允许我们将一个值与一系列的模式相比较&#xff0c;并根据相匹配的模式执行相应代码。 1 枚举的定义 假设我们要跨省出行&#xff0c;有多种交通工具供选择。常用的交通工具有飞机、火车、汽车和轮…

备战蓝桥杯Day37 - 真题 - 特殊日期

一、题目描述 思路&#xff1a; 1、统计2000年到2000000年的日期&#xff0c;肯定是需要遍历 2、闰年的2月是29天&#xff0c;非闰年的2月是28天。我们需要判断这一年是否是闰年。 1、3、5、7、8、10、12月是31天&#xff0c;4、6、9、11月是30天。 3、年份yy是月份mm的倍数…

【Entity Framework】EF配置文件设置详解

【Entity Framework】EF配置文件设置详解 文章目录 【Entity Framework】EF配置文件设置详解一、概述二、实体框架配置部分三、连接字符串四、EF数据库提供程序五、EF侦听器六、将数据库操作记录到文件中七、Code First默认连接工厂八、数据库初始值设定项 一、概述 EF实体框架…

OKR应用层级与试点部门选择:管理层与员工层的应用探讨

OKR&#xff08;Objectives and Key Results&#xff09;作为一种高效的目标管理工具&#xff0c;其应用层级的选择对于企业的实施效果至关重要。在管理层和员工层之间&#xff0c;并没有绝对的先后顺序&#xff0c;而是需要根据企业的具体情况和需求进行灵活应用。同时&#x…

CODEFORCES --- 630A. Again Twenty Five!

630A. Again Twenty Five! 人力资源经理又失望了。最后一名应聘者和之前的 24 名应聘者一样&#xff0c;都没有通过面试。"我应该给这样一个艰巨的任务吗&#xff1f;- 人力资源经理想。“只要把数字 5 提高到 n 的幂&#xff0c;然后得到数字的最后两位就可以了。是的&a…

stata 数据匹配

横向匹配&#xff08;增加变量&#xff09;——merge merge 1:1 id using otherfile.dta匹配城市 merge m:1 city using "E:\基点.dta",nogen匹配上市公司 merge m:1 stkcd time using "E:\基点.dta",nogen匹配类型&#xff1a; 1:1: 1配1 m:1:多配1 …

QEMU介绍

原文位置&#xff1a;https://github.com/qemu/qemu 原文 QEMU is a generic and open source machine & userspace emulator and virtualizer. QEMU is capable of emulating a complete machine in software without any need for hardware virtualization support. B…