Lambda 重构面向对象的设计模式

Lambda 重构面向对象的设计模式

策略模式

策略模式包含三部分内容
一个代表某个算法的接口(它是策略模式的接口)。
一个或多个该接口的具体实现,它们代表了算法的多种实现(比如,实体类ConcreteStrategyA或者ConcreteStrategyB)。
一个或多个使用策略对象的客户

public interface ValidationStrategy { boolean execute(String s); 
}public class IsAllLowerCase implements ValidationStrategy { public boolean execute(String s){ return s.matches("[a-z]+"); } 
} 
public class IsNumeric implements ValidationStrategy { public boolean execute(String s){ return s.matches("\\d+"); } 
}public class Validator{ private final ValidationStrategy strategy; public Validator(ValidationStrategy v){ this.strategy = v;  } public boolean validate(String s){ return strategy.execute(s); } 
} 
Validator numericValidator = new Validator(new IsNumeric()); 
boolean b1 = numericValidator.validate("aaaa"); 
Validator lowerCaseValidator = new Validator(new IsAllLowerCase ()); 
boolean b2 = lowerCaseValidator.validate("bbbb"); 
Validator numericValidator =  new Validator((String s) -> s.matches("[a-z]+")); 
boolean b1 = numericValidator.validate("aaaa"); 
Validator lowerCaseValidator = new Validator((String s) -> s.matches("\\d+")); 
boolean b2 = lowerCaseValidator.validate("bbbb");

Lambda表达式避免了采用策略设计模式时僵化的模板代码。如果你仔细分 析一下个中缘由,可能会发现,Lambda表达式实际已经对部分代码(或策略)进行了封装,而 这就是创建策略设计模式的初衷。因此,我们强烈建议对类似的问题,你应该尽量使用Lambda 表达式来解决

模板方法

让我们从一个例子着手,看看这个模式是如何工作的。假设你需要编写一个简单的在线银行 应用。通常,用户需要输入一个用户账户,之后应用才能从银行的数据库中得到用户的详细信息, 最终完成一些让用户满意的操作。不同分行的在线银行应用让客户满意的方式可能还略有不同, 比如给客户的账户发放红利,或者仅仅是少发送一些推广文件。你可能通过下面的抽象类方式来 实现在线银行应用

abstract class OnlineBanking { public void processCustomer(int id){ Customer c = Database.getCustomerWithId(id); makeCustomerHappy(c); }abstract void makeCustomerHappy(Customer c); 
} 

使用Lambda表达式

public void processCustomer(int id, Consumer<Customer> makeCustomerHappy){ Customer c = Database.getCustomerWithId(id); makeCustomerHappy.accept(c); 
} new OnlineBankingLambda().processCustomer(1337, (Customer c) -> System.out.println("Hello " + c.getName()); 

观察者模式

interface Observer { void notify(String tweet); 
}class NYTimes implements Observer{ public void notify(String tweet) { if(tweet != null && tweet.contains("money")){ System.out.println("Breaking news in NY! " + tweet); } } 
} 
class Guardian implements Observer{ public void notify(String tweet) { if(tweet != null && tweet.contains("queen")){ System.out.println("Yet another news in London... " + tweet); } } 
} 
class LeMonde implements Observer{ public void notify(String tweet) { if(tweet != null && tweet.contains("wine")){ System.out.println("Today cheese, wine and news! " + tweet); } } 
} interface Subject{ void registerObserver(Observer o); void notifyObservers(String tweet); 
} class Feed implements Subject{ private final List<Observer> observers = new ArrayList<>(); public void registerObserver(Observer o) { this.observers.add(o); } public void notifyObservers(String tweet) { observers.forEach(o -> o.notify(tweet)); } 
}Feed f = new Feed(); 
f.registerObserver(new NYTimes()); 
f.registerObserver(new Guardian()); 
f.registerObserver(new LeMonde()); 
f.notifyObservers("The queen said her favourite book is Java 8 in Action!"); 

使用Lambda表达式

f.registerObserver((String tweet) -> { if(tweet != null && tweet.contains("money")){ System.out.println("Breaking news in NY! " + tweet); } 
}); 
f.registerObserver((String tweet) -> { if(tweet != null && tweet.contains("queen")){ System.out.println("Yet another news in London... " + tweet); } 
}); 

那么,是否我们随时随地都可以使用Lambda表达式呢?答案是否定的!我们前文介绍的例 子中,Lambda适配得很好,那是因为需要执行的动作都很简单,因此才能很方便地消除僵化代 码。但是,观察者的逻辑有可能十分复杂,它们可能还持有状态,抑或定义了多个方法,诸如此 类。在这些情形下,你还是应该继续使用类的方式

责任链模式

通常,这种模式是通过定义一个代表处理对象的抽象类来实现的,在抽象类中会定义一个字 段来记录后续对象。一旦对象完成它的工作,处理对象就会将它的工作转交给它的后继。代码中, 这段逻辑看起来是下面这样

public abstract class ProcessingObject<T> { protected ProcessingObject<T> successor; public void setSuccessor(ProcessingObject<T> successor){ this.successor = successor;} public T handle(T input){ T r = handleWork(input); if(successor != null){ return successor.handle(r); } return r; } abstract protected T handleWork(T input); 
} public class HeaderTextProcessing extends ProcessingObject<String> { public String handleWork(String text){ return "From Raoul, Mario and Alan: " + text; } 
} 
public class SpellCheckerProcessing extends ProcessingObject<String> { public String handleWork(String text){ return text.replaceAll("labda", "lambda"); } 
} ProcessingObject<String> p1 = new HeaderTextProcessing(); 
ProcessingObject<String> p2 = new SpellCheckerProcessing(); 
p1.setSuccessor(p2);
String result = p1.handle("Aren't labdas really sexy?!!"); 
System.out.println(result); 

使用Lambda表达式

UnaryOperator<String> headerProcessing =  (String text) -> "From Raoul, Mario and Alan: " + text;
UnaryOperator<String> spellCheckerProcessing =  (String text) -> text.replaceAll("labda", "lambda"); 
Function<String, String> pipeline =  headerProcessing.andThen(spellCheckerProcessing); 
String result = pipeline.apply("Aren't labdas really sexy?!!")

工厂模式

public class ProductFactory { public static Product createProduct(String name){ switch(name){ case "loan": return new Loan(); case "stock": return new Stock(); case "bond": return new Bond(); default: throw new RuntimeException("No such product " + name); } } 
} 
Product p = ProductFactory.createProduct("loan"); 

使用Lambda表达式

final static Map<String, Supplier<Product>> map = new HashMap<>(); 
static { map.put("loan", Loan::new); map.put("stock", Stock::new); map.put("bond", Bond::new); 
} public static Product createProduct(String name){ Supplier<Product> p = map.get(name); if(p != null) return p.get(); throw new IllegalArgumentException("No such product " + name); 
} 

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

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

相关文章

java集成poi框架

介绍 : Apache POI是Apache软件基金会的开放源码函式库&#xff0c;POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 下面简单介绍一下如何使用该框架&#xff1a; 一&#xff1a;导入依赖 <!-- excel解析依赖--><dependency><groupId&…

17 redis集群方案

1、RedisCluster分布式集群解决方案 为了解决单机内存&#xff0c;并发等瓶颈&#xff0c;可使用此方案解决问题. Redis-cluster是一种服务器Sharding技术&#xff0c;Redis3.0以后版本正式提供支持。 这里的集群是指多主多从&#xff0c;不是一主多从。 2、redis集群的目标…

pair和typedef

文章目录 一、pair用法1.2、pair的创建和初始化1.3、pair对象的操作1.4、(make_pair)生成新的pair对象1.5、通过tie获取pair元素值 2、typedef2.1、什么是typedef2.2、typedef用法2.2.1、对于数据类型使用例如&#xff1a;2.2.2、对于指针的使用例如2.2.3、对于结构体的使用 2.…

java springboot测试类虚拟MVC环境 匹配返回值与预期内容是否相同 (JSON数据格式) 版

上文java springboot测试类鉴定虚拟MVC请求 返回内容与预期值是否相同我们讲了测试类中 虚拟MVC发送请求 匹配返回内容是否与预期值相同 但是 让我意外的是 既然没人骂我 因为我们实际开发 返回的基本都是json数据 字符串的接口场景是少数的 我们在java文件目录下创建一个 dom…

2023年10月纸巾市场分析(京东天猫淘宝平台纸巾品类数据采集)

双十一大促期间&#xff0c;刚需品的纸巾是必囤商品之一。今年双十一&#xff0c;京东数据显示&#xff0c;10月23日至29日&#xff0c;清洁纸品成交额同比增长40%&#xff0c;由此也拉动了10月纸巾市场的销售。 鲸参谋数据显示&#xff0c;今年10月&#xff0c;京东平台纸巾市…

【日常总结】如何禁止浏览器 http自动跳转成https

一、场景 二、问题 三、解决方案 3.1 chrome 浏览器 3.2 edge 浏览器&#xff1a; 3.3 Safari 浏览器 3.4 Firefox 浏览器 3.5 Microsoft Edge 一、场景 公司网站 http:// 谷歌浏览器中自动转换成 https:// 导致无法访问 二、问题 nginx配置ssl 443接口&#xff0c; ht…

SOLIDWORKS 2024新功能之Electrical篇

SOLIDWORKS 2024 Electrical篇目录概览 • 对齐零部件 • 更改多个导轨和线槽的长度 • 过滤辅助和附件零件 • 2D 机柜中的自动零件序号 • 移除制造商零件数据 • 重置未定义的宏变量 • 使用范围缩短列表 • SOLIDWORKS Electrical Schematic 增强功能 1、对齐零部件…

ONNX实践系列-修改yolov5-seg的proto分支输出shape

一、目标 本文主要介绍要将原始yolov5分割的输出掩膜从[b,c,h,.w]修改为[b, h, w, c] 原来的: 目标的: 代码如下: Descripttion: version: @Company: WT-XM Author: yang jinyi Date: 2023-09-08 11:26:28 LastEditors: yang jinyi LastEditTime: 2023-09-08 11:48:01 …

Threejs_14 制作圣诞贺卡

继续跟着老陈打码学习&#xff01;&#xff01;&#xff01;支持&#xff01;&#xff01;&#xff01; 效果图 链接&#xff1a;https://pan.baidu.com/s/1Ft8U2HTeqmpyAeesL31iUg 提取码&#xff1a;6666 使用到的 模型文件和资源等都为老陈打码提供&#xff01;&#x…

【腾讯云云上实验室】探索保护数据之盾背后的安全监控机制

当今数字化时代&#xff0c;数据安全成为了企业和个人最为关注的重要议题之一。随着数据规模的不断增长和数据应用的广泛普及&#xff0c;如何保护数据的安全性和隐私性成为了迫切的需求。 今天&#xff0c;我将带领大家一起探索腾讯云云上实验室所推出的向量数据库&#xff0c…

新版PY系列离线烧录器,支持PY002A/002B/003/030/071等MCU各封装,不同 FLASH 大小型号

PY系列离线烧录器&#xff0c;目前支持PY32F002A/002B/002/003/030/071/072/040/403/303 各封装、不同 FLASH 大小型号。PY离线烧录器需要搭配上位机软件使用&#xff0c;上位机软件可以在芯岭技术官网上下载&#xff0c;还包括了离线烧录器的使用说明。PY离线烧录器使用MINI U…

金融机构如何高效率考勤?这个技巧帮了大忙!

在现代社会&#xff0c;随着科技的不断发展&#xff0c;人脸识别技术作为一种高效、便捷的身份验证手段&#xff0c;逐渐应用于各个领域&#xff0c;其中之一便是人脸考勤系统。 传统的考勤方式存在一系列问题&#xff0c;如卡片打卡容易被冒用、签到表容易造假等&#xff0c;而…

CTFUB-web前置技能-HTTP协议

burp抓包,抓第二次的 修改请求方式为CTFHUB

算法笔记:OPTICS 聚类

1 基本介绍 OPTICS(Ordering points to identify the clustering structure)是一基于密度的聚类算法 OPTICS算法是DBSCAN的改进版本 在DBCSAN算法中需要输入两个参数&#xff1a; ϵ 和 MinPts &#xff0c;选择不同的参数会导致最终聚类的结果千差万别&#xff0c;因此DBCSAN…

线上PDF文件展示

场景&#xff1a; 请求到的PDF&#xff08;url链接&#xff09;&#xff0c;将其展示在页面上 插件&#xff1a; pdfobject &#xff08;我使用的版本&#xff1a; "pdfobject": "^2.2.12" &#xff09; 下载插件就不多说了&#xff0c;下面将其引入&a…

【Clang Static Analyzer 代码静态检测工具详细使用教程】

Clang Static Analyzer sudo apt-get install clang-tools scan-build cmake .. scan-build make -j4 编译完成之后会在终端提示在哪里查看报错文档: scan-build: 55 bugs found. scan-build: Run scan-view /tmp/scan-build-2023-11-24-150637-6472-1 to examine bug report…

Liunx Ubuntu Server 安装配置 Docker

1. 安装Docker 1.1 更新软件包列表 sudo apt update1.2 添加Docker存储库 sudo apt install apt-transport-https ca-certificates curl gnupg-agent software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-a…

Django QuerySet.order_by SQL注入漏洞(CVE-2021-35042)

漏洞描述 Django 于 2021年7月1日发布了一个安全更新&#xff0c;修复了函数QuerySet.order_by中的 SQL 注入漏洞。 参考链接&#xff1a; Django security releases issued: 3.2.5 and 3.1.13 | Weblog | Django 该漏洞需要开发人员使用order_by功能。此外&#xff0c;还可…

加入华为云鲲鹏极简开发创造营,激活创造力,探索无限可能!

数字经济时代&#xff0c;速度、效率、质量安全已成为各行业告诉拓新发展的关键&#xff0c;华为云不断打磨敏捷安全开发的软件平台&#xff0c;为更高效率的生产力变革积蓄能量。 在刚刚过去不久的2023华为全联接大会上&#xff0c;华为最新发布了华为云CodeArts与鲲鹏DevKit…

关于配置文件中秘钥信息加密实现方案的一些思考

关于配置文件中秘钥信息加密实现方案的一些思考 背景实现方案 背景 配置信息文件中(代码中), 不应该有明文的秘钥信息. 需要找一种方案去做加密处理. 实现方案 我们可以在项目指定目录上传一份加密/解密程序, 例如: jasypt-gui.jar. 启动时: 配置JVM参数, 对加密的信息进行解…