【函数式接口使用✈️✈️】配合策略模式实现文件处理的案例

server/2024/10/18 19:23:16/

目录

🍸前言

🍻一、功能描述

🍺二、面向对象设计模式

🍹三、策略模式

🍦四、策略 VS 面向对象

🍨章末


🍸前言

        小伙伴们大家好,上周初步了解了下函数式接口,Consumer,Supplier,Function等接口的使用,以及结合而策略模式实现购物促销功能的案例实现,这里再配合实现文件处理的功能,案例比较简单,主要是看策略模式和普通面向对象模式的区别

🍻一、功能描述

假设我们需要实现一个文件处理器,能够读取文件内容,并根据不同的处理策略对文件内容进行处理,例如将文件内容转换为大写、小写或者进行加密。

🍺二、面向对象设计模式

       (1) 这种方式逻辑比较清晰,就是创建一个文件处理器类,该类中有各种文件内容处理方法,比如内容转大写或者加密,文件处理器类如下:

java">import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;public class FileProcessor {public void processFileToUpper(String filename) throws IOException {try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {String line;while ((line = reader.readLine()) != null) {String processedLine = line.toUpperCase();System.out.println(processedLine); // 可替换为具体处理逻辑,比如写入到另一个文件}}}public void processFileToLower(String filename) throws IOException {try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {String line;while ((line = reader.readLine()) != null) {String processedLine = line.toLowerCase();System.out.println(processedLine); }}}public void processFileEncrypt(String filename) throws IOException {try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {String line;while ((line = reader.readLine()) != null) {// 这里只是演示,实际的加密算法应该更复杂String processedLine = line.replaceAll("[a-zA-Z]", "*");System.out.println(processedLine); }}}
}

        (2)测试下,使用很简单,实例化一个文件处理器对象,通过对象调用其具体的处理方法即可

java">import java.io.IOException;public class TestFile {public static void main(String[] args) {String filename = "C:\\Users\\ben.huang\\Desktop\\testFile.txt";FileProcessor fileProcessor = new FileProcessor();try {System.out.println("File content in uppercase:");fileProcessor.processFileToUpper(filename);System.out.println("\nFile content in lowercase:");fileProcessor.processFileToLower(filename);System.out.println("\nFile content encrypted:");fileProcessor.processFileEncrypt(filename);} catch (IOException e) {e.printStackTrace();}}
}

🍹三、策略模式

        (1)也是创建一个文件处理器类,不过该类中只有一个处理方法,具体地 实现功能要根据传入地函数名称去处理,文件处理器类如下:

java">import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;/*** @author ben.huang*/
public class FileFunction {public void processFile (String fileName, Function<String,String> processingStrategy) throws IOException {//supplier 相当于生产者,调用该函数会获取到文件地读取流Supplier<BufferedReader> fileReadSupplier = () ->{try {return new BufferedReader(new FileReader(fileName));} catch (FileNotFoundException e) {throw new RuntimeException("error opening file"+e);}};//相当于一个消费者,根据传入的函数去消费每一行读取到地数据Consumer<String> fileProcessor = line ->{String apply = processingStrategy.apply(line);System.out.println(apply);};//获取输入流BufferedReader reader = fileReadSupplier.get();String line;//依次处理每行输入流while((line = reader.readLine()) != null){fileProcessor.accept(line);}}
}

         (2)具体地文件处理函数可以单独写到一个类中,因为后期如果需要添加新的处理函数,直接在这里进行扩展即可,文件处理函数如下:

java">import java.util.function.Function;/*** @author ben.huang*/
public class FileProcessingStrategies {//返回的是函数表达式public static Function<String,String> toUpperCase(){return String::toUpperCase;}public static Function<String,String> toLowerCase(){return String::toLowerCase;}public static Function<String,String> encrypt(){return str -> str.replaceAll("[a-zA-Z]","*");}
}

        (3)测试下

java">import java.io.IOException;/*** @author ben.huang*/
public class TestFileFunction {public static void main(String[] args) {String fileName = "C:\\Users\\ben.huang\\Desktop\\testFile.txt";FileFunction fileFunction = new FileFunction();try {//方法调用的时候,传入需要的处理函数即可System.out.println("File content in uppercase:");fileFunction.processFile(fileName,FileProcessingStrategies.toUpperCase());System.out.println("\nFile content in lowercase:");fileFunction.processFile(fileName,FileProcessingStrategies.toLowerCase());System.out.println("\nFile content in encrypted:");fileFunction.processFile(fileName,FileProcessingStrategies.encrypt());} catch (IOException e) {throw new RuntimeException(e);}}
}

🍦四、策略 VS 面向对象

         首先来看面向对象设计模式,这种方式是我在初学地时候最喜欢的编码方式,这种逻辑方便观看,易读性强,调用方便,代码方便别人阅读,修改方便,直接CV修改修改就行,整个功能在一个类中全部实现,省了来回跳看的眼花,还有....(等等,串台了(bushi))

        那我们为社么还要用策略模式呢?

不知大家可曾听闻开闭原则,依鄙人来看就是说不要去修改原有的类,而是去扩展。比如说,现在又加了几个文件处理器功能,策略模式只需要在策略函数类中新增几个函数,如果使用面向对象的话,需要新增几个方法,并且这些方法中有很多代码重复,冗余度很高

        总的来说,策略模式更加直接,通过定义不同的策略类来实现不同的功能,并且可以在运行时动态切换策略。而面向对象设计模式则更加灵活,可以根据具体的需求选择不同的设计模式来实现文件处理功能

🍬后续补充

        用的比较少的话还是生疏,再给大家举几案例吧

🍧案例一、比如根据不同的商品进行不同的税费计算

        分析:按照不同商品进行计算处理,简单的方法就是使用 if else 判断属于哪种商品,然后进行对应的计算操作。使用策略模式是这样,每个商品都要计算,那么可以把计算操作当作一个接口,不同的计算逻辑可以实现该接口,然后创建一个处理类,包含具体的计算实现类,以及调用实现类方法,代码如下:
        (1)计算方法接口定义

java">interface TaxStrategy {double calculateTax(double amount);
}

        (2)计算方法具体实现类

java">class BasicTaxStrategy implements TaxStrategy {@Overridepublic double calculateTax(double amount) {return amount * 0.1; // 基本税率为10%}
}class LuxuryTaxStrategy implements TaxStrategy {@Overridepublic double calculateTax(double amount) {return amount * 0.2; // 奢侈品税率为20%}
}class FoodTaxStrategy implements TaxStrategy {@Overridepublic double calculateTax(double amount) {return amount * 0.05; // 食品税率为5%}
}

         (3)计算处理类,使用 Function 函数式接口代表具体的计算策略,构造方法接收一个函数参数,处理方法中的  apply 方法会接受一个参数,处理后返回一个参数

java">class TaxCalculator {private Function<Double, Double> taxStrategy;public TaxCalculator(Function<Double, Double> taxStrategy) {this.taxStrategy = taxStrategy;}public double calculateTax(double amount) {return taxStrategy.apply(amount);}
}//使用的时候像这样,传入一个实现类,则调用的就是这个实现类的计算方法//TaxCalculator taxCalculator = new TaxCalculator(new BasicTaxStrategy()::calculateTax);//double calculate = taxCalculator.calculate(100);

🍨章末

        文章到这里就结束了~


http://www.ppmy.cn/server/15313.html

相关文章

AIGC实战——基于Transformer实现音乐生成

AIGC实战——基于Transformer实现音乐生成 0. 前言1. 音乐生成的挑战2. MuseNet3. 音乐数据3.1 巴赫大提琴组曲数据集3.2 解析 MIDI 文件3.3 分词3.4 创建训练数据集 4. MuseNet 模型4.1 正弦位置编码4.2 多输入/输出 5. 音乐生成 Transformer 的分析6. 多声部音乐分词6.1 网格…

Python 0基础_变现_38岁_day 15(匿名函数)

匿名函数&#xff1a; 不用定义函数名&#xff0c;无需使用def关键字&#xff0c;使用lambda将函数写成一行&#xff1b;#使用匿名函数定义一个两个数字相加的函数add lambda x,y : xy #使用变量接收匿名函数的内容&#xff0c;且变量名作为调用函数的变量名&#xff1…

tcp客户端向tcp服务器发送json文件,服务器转存为json文件

客户端&#xff1a; void socket::send_msg(QString file_name) {qDebug() <<"socket::send_msg(QString file_name):" << QThread::currentThread();//读取json文件QFile file(file_name); // fileName文件的路径if (file.open(QIODevice::ReadOnly)) …

vue快速入门(三十八)v-modle简化父子组件的数据双向绑定

注释很详细&#xff0c;直接上代码 上一篇 新增内容 v-model 原理解析v-model 组件双向绑定示范 源码 MyTest.vue <template><div id"MyTest"><select :value"value" change"handleChange"><option value"广东"…

Redis系列:内存淘汰策略

1 前言 通过前面的一些文章我们知道&#xff0c;Redis的各项能力是基于内存实现的&#xff0c;相对其他的持久化存储&#xff08;如MySQL、File等&#xff0c;数据持久化在磁盘上&#xff09;&#xff0c;性能会高很多&#xff0c;这也是高速缓存的一个优势。 但是问题来了&am…

【ES】springboot集成ES

1. 去Spring官方文档确认版本兼容性 这一版的文档里没有给出springboot的版本对应&#xff0c;但我在一个博主的文章里看到的es8.0以前的官方文档中就有给出来&#xff0c;所以还需要再去寻找spring framework和springboot的对应关系&#xff1f;&#xff1f;&#xff1f; 还…

浅谈AVL树,红黑树,B树,B+树原理及应用

大家有没有产生这样一个疑问,对于数据索引&#xff0c;为什么要使用BTree这种数据结构&#xff0c;和其它树相比&#xff0c;它能体现的优点在哪里&#xff1f; 看完这篇文章你就会了解到这些数据结构的原理以及它们各自的应用场景。 二叉查找树 简介 二叉查找树也称为有序二…

C++ 几句话彻底点通虚表

#include <iostream>using namespace std;class Base { public:virtual void show() // 声明虚函数{cout << "Base" << endl;} };class Derived : public Base { public:void show() override // 覆盖虚函数{cout << "Derived" &l…