目录

· 改写设计模式

· 策略模式(Strategy Pattern)

· 模板方法模式(Template Method Pattern)

· 观察者模式(Observer Pattern)

· 责任链模式(Chain of Responsibility Pattern)

· 简单工厂模式(Simple Factory Pattern)

· 高阶函数与柯里化


改写设计模式

策略模式(Strategy Pattern)

1. 改写前

a) ValidationStrategy.java

  1. public interface ValidationStrategy {
  2.  
  3. boolean execute(String s);
  4.  
  5. }

b) IsNumeric.java

  1. public class IsNumeric implements ValidationStrategy {
  2.  
  3. public boolean execute(String s) {
  4. return s.matches("\\d+");
  5. }
  6.  
  7. }

c) IsAllLowerCase.java

  1. public class IsAllLowerCase implements ValidationStrategy {
  2.  
  3. public boolean execute(String s) {
  4. return s.matches("[a-z]+");
  5. }
  6.  
  7. }

d) Validator.java

  1. public class Validator {
  2. private final ValidationStrategy strategy;
  3.  
  4. public Validator(ValidationStrategy v) {
  5. this.strategy = v;
  6. }
  7.  
  8. public boolean validate(String s) {
  9. return strategy.execute(s);
  10. }
  11. }

e) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. Validator numericValidator = new Validator(new IsNumeric());
  5. boolean b1 = numericValidator.validate("aaaa");
  6. System.out.println(b1); // false
  7. Validator lowerCaseValidator = new Validator(new IsAllLowerCase());
  8. boolean b2 = lowerCaseValidator.validate("bbbb");
  9. System.out.println(b2); // true
  10. }
  11.  
  12. }

2.改写后

a) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. Validator numericValidator = new Validator((String s) -> s.matches("\\d+"));
  5. boolean b1 = numericValidator.validate("aaaa");
  6. System.out.println(b1); // false
  7. Validator lowerCaseValidator = new Validator(s -> s.matches("[a-z]+"));
  8. boolean b2 = lowerCaseValidator.validate("bbbb");
  9. System.out.println(b2); // true
  10. }
  11.  
  12. }

模板方法模式(Template Method Pattern)

1. 改写前

a) Customer.java

  1. public class Customer {
  2.  
  3. private int id;
  4. private String name;
  5.  
  6. public Customer(int id, String name) {
  7. this.id = id;
  8. this.name = name;
  9. }
  10.  
  11. public int getId() {
  12. return id;
  13. }
  14.  
  15. public void setId(int id) {
  16. this.id = id;
  17. }
  18.  
  19. public String getName() {
  20. return name;
  21. }
  22.  
  23. public void setName(String name) {
  24. this.name = name;
  25. }
  26.  
  27. }

b) OnlineBanking.java

  1. public abstract class OnlineBanking {
  2.  
  3. public void processCustomer(int id) {
  4. Customer c = new Customer(id, "Jhon");
  5. makeCustomerHappy(c);
  6. }
  7.  
  8. abstract void makeCustomerHappy(Customer c);
  9.  
  10. }

2.改写后

a) OnlineBankingLambda.java

  1. import java.util.function.Consumer;
  2.  
  3. public class OnlineBankingLambda {
  4.  
  5. public void processCustomer(int id, Consumer<Customer> makeCustomerHappy) {
  6. Customer c = new Customer(id, "Jhon");
  7. makeCustomerHappy.accept(c);
  8. }
  9.  
  10. }

b) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. new OnlineBankingLambda().processCustomer(1337, (Customer c) -> System.out.println("Hello " + c.getName()));
  5. }
  6.  
  7. }

观察者模式(Observer Pattern)

1. 改写前

a) Observer.java

  1. public interface Observer {
  2.  
  3. void notify(String tweet);
  4.  
  5. }

b) NYTimes.java

  1. public class NYTimes implements Observer {
  2.  
  3. public void notify(String tweet) {
  4. if (tweet != null && tweet.contains("money")) {
  5. System.out.println("Breaking news in NY! " + tweet);
  6. }
  7. }
  8.  
  9. }

c) Guardian.java

  1. public class Guardian implements Observer {
  2.  
  3. public void notify(String tweet) {
  4. if (tweet != null && tweet.contains("queen")) {
  5. System.out.println("Yet another news in London... " + tweet);
  6. }
  7. }
  8.  
  9. }

d) LeMonde.java

  1. public class LeMonde implements Observer {
  2.  
  3. public void notify(String tweet) {
  4. if (tweet != null && tweet.contains("wine")) {
  5. System.out.println("Today cheese, wine and news! " + tweet);
  6. }
  7. }
  8.  
  9. }

e) Subject.java

  1. public interface Subject {
  2.  
  3. void registerObserver(Observer o);
  4.  
  5. void notifyObservers(String tweet);
  6.  
  7. }

f) Feed.java

  1. public class Feed implements Subject {
  2.  
  3. private final List<Observer> observers = new ArrayList<>();
  4.  
  5. public void registerObserver(Observer o) {
  6. this.observers.add(o);
  7. }
  8.  
  9. public void notifyObservers(String tweet) {
  10. observers.forEach(o -> o.notify(tweet));
  11. }
  12.  
  13. }

g) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. Feed f = new Feed();
  5. f.registerObserver(new NYTimes());
  6. f.registerObserver(new Guardian());
  7. f.registerObserver(new LeMonde());
  8. f.notifyObservers("The queen said her favourite book is Java 8 in Action!");
  9. }
  10.  
  11. }

2.改写后

a) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. Feed f = new Feed();
  5. f.registerObserver((String tweet) -> {
  6. if (tweet != null && tweet.contains("money")) {
  7. System.out.println("Breaking news in NY! " + tweet);
  8. }
  9. });
  10. f.registerObserver((tweet) -> {
  11. if (tweet != null && tweet.contains("queen")) {
  12. System.out.println("Yet another news in London... " + tweet);
  13. }
  14. });
  15. f.registerObserver((tweet) -> {
  16. if (tweet != null && tweet.contains("wine")) {
  17. System.out.println("Today cheese, wine and news! " + tweet);
  18. }
  19. });
  20. f.notifyObservers("The queen said her favourite book is Java 8 in Action!");
  21. }
  22.  
  23. }

责任链模式(Chain of Responsibility Pattern)

1. 改写前

a) ProcessingObject.java

  1. public abstract class ProcessingObject<T> {
  2.  
  3. protected ProcessingObject<T> successor;
  4.  
  5. public void setSuccessor(ProcessingObject<T> successor) {
  6. this.successor = successor;
  7. }
  8.  
  9. public T handle(T input) {
  10. T r = handleWork(input);
  11. if (successor != null) {
  12. return successor.handle(r);
  13. }
  14. return r;
  15. }
  16.  
  17. protected abstract T handleWork(T input);
  18. }

b) HeaderTextProcessing.java

  1. public class HeaderTextProcessing extends ProcessingObject<String> {
  2.  
  3. public String handleWork(String text) {
  4. return "From Raoul, Mario and Alan: " + text;
  5. }
  6.  
  7. }

c) SpellCheckerProcessing.java

  1. public class SpellCheckerProcessing extends ProcessingObject<String> {
  2.  
  3. public String handleWork(String text) {
  4. return text.replaceAll("labda", "lambda");
  5. }
  6.  
  7. }

d) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. ProcessingObject<String> p1 = new HeaderTextProcessing();
  5. ProcessingObject<String> p2 = new SpellCheckerProcessing();
  6. p1.setSuccessor(p2);
  7. String result = p1.handle("Aren't labdas really sexy?!!");
  8. System.out.println(result);
  9. }
  10.  
  11. }

2.改写后

a) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. UnaryOperator<String> headerProcessing = (String text) -> "From Raoul, Mario and Alan: " + text;
  5. UnaryOperator<String> spellCheckerProcessing = (String text) -> text.replaceAll("labda", "lambda");
  6. Function<String, String> pipeline = headerProcessing.andThen(spellCheckerProcessing);
  7. String result = pipeline.apply("Aren't labdas really sexy?!!");
  8. System.out.println(result);
  9. }
  10.  
  11. }

简单工厂模式(Simple Factory Pattern)

1. 改写前

a) Product.java

  1. public interface Product {
  2. }

b) Loan.java

  1. public class Loan implements Product {
  2. }

c) Stock.java

  1. public class Stock implements Product {
  2. }

d) Bond.java

  1. public class Bond implements Product {
  2. }

e) ProductFactory.java

  1. public class ProductFactory {
  2.  
  3. public static Product createProduct(String name) {
  4. switch (name) {
  5. case "loan":
  6. return new Loan();
  7. case "stock":
  8. return new Stock();
  9. case "bond":
  10. return new Bond();
  11. default:
  12. throw new RuntimeException("No such product " + name);
  13. }
  14. }
  15.  
  16. }

f) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. Product p = ProductFactory.createProduct("loan");
  5. }
  6.  
  7. }

2. 改写后

a) ProductFactory.java

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.function.Supplier;
  4.  
  5. public class ProductFactory {
  6.  
  7. final static Map<String, Supplier<Product>> map = new HashMap<>();
  8.  
  9. static {
  10. map.put("loan", Loan::new);
  11. map.put("stock", Stock::new);
  12. map.put("bond", Bond::new);
  13. }
  14.  
  15. public static Product createProduct(String name) {
  16. Supplier<Product> p = map.get(name);
  17. if (p != null) return p.get();
  18. throw new IllegalArgumentException("No such product " + name);
  19. }
  20.  
  21. }

b) Test.java

  1. public class Test {
  2.  
  3. public static void main(String[] args) {
  4. Product p = ProductFactory.createProduct("loan");
  5. }
  6.  
  7. }

高阶函数与柯里化

1. 高阶函数(Higher-order Function):满足以下任意一个条件都是高阶函数。

a) 接受至少一个函数作为参数。

b) 返回的结果是一个函数。

2. 柯里化(Currying):假设有一个函数 f(x, y) ,柯里化就是把多个参数的函数f转化为一个参数的函数g,并且函数g的返回值一个新函数,即 f(x, y) = (g(x))(y) 。

3. 柯里化好处:灵活、复用。

4. 举例

a) 柯里化前

  1. public class Test {
  2.  
  3. public static double converter(double x, double f, double b) {
  4. return x * f + b;
  5. }
  6.  
  7. public static void main(String[] args) {
  8. double gbp = converter(1000, 0.6, 0);
  9. System.out.println(gbp);
  10. }
  11.  
  12. }

b) 柯里化后

  1. public class Test {
  2.  
  3. public static DoubleUnaryOperator curriedConverter(double f, double b) {
  4. return (double x) -> x * f + b;
  5. }
  6.  
  7. public static void main(String[] args) {
  8. DoubleUnaryOperator convertCtoF = curriedConverter(9.0 / 5, 32);
  9. DoubleUnaryOperator convertUSDtoGBP = curriedConverter(0.6, 0);
  10. DoubleUnaryOperator convertKmtoMi = curriedConverter(0.6214, 0);
  11.  
  12. double gbp = convertUSDtoGBP.applyAsDouble(1000);
  13. System.out.println(gbp);
  14. }
  15.  
  16. }

作者:netoxi
出处:http://www.cnblogs.com/netoxi
本文版权归作者和博客园共有,欢迎转载,未经同意须保留此段声明,且在文章页面明显位置给出原文连接。欢迎指正与交流。


3分钟看完Java 8——史上最强Java 8新特性总结之第三篇 函数式编程技巧的更多相关文章

  1. 3分钟看完Java 8——史上最强Java 8新特性总结之第二篇 Stream API

    目录 · 概况 · 切片(Slicing) · 映射(Mapping) · 匹配(Matching) · 查找(Finding) · 归约(Reducing) · 排序(Sorting) · 数值流( ...

  2. 3分钟看完Java 8——史上最强Java 8新特性总结之第一篇 函数式编程基础

    目录 · 行为参数化 · Lambda表达式 · 概况 · 函数式接口 · 类型推断 · 使用外层变量 · 方法引用 · 复合Lambda表达式 行为参数化 1. 理解函数式编程要先理解行为参数化. ...

  3. 3分钟看完Java 8——史上最强Java 8新特性总结之第四篇 其他新特性

    目录 · 默认方法和静态方法 · 初步理解 · 应用模式 · 优先级问题 · Optional · CompletableFuture · 基本用法 · CompletableFuture与Strea ...

  4. 史上最强Java NIO入门:担心从入门到放弃的,请读这篇!

    本文原题“<NIO 入门>,作者为“Gregory M. Travis”,他是<JDK 1.4 Tutorial>等书籍的作者. 1.引言 Java NIO是Java 1.4版 ...

  5. 金九银十,史上最强 Java 面试题整理。

    以下会重新整理所有 Java 系列面试题答案.及各大互联网公司的面试经验,会从以下几个方面汇总,本文会长期更新. Java 面试篇 史上最全 Java 面试题,带全部答案 史上最全 69 道 Spri ...

  6. 史上最强Java开发环境搭建

    在项目产品开发中,开发环境搭建是软件开发的首要阶段,也是必须阶段,只有开发环境搭建好了,方可进行开发,良好的开发环境搭建,为后续的开发工作带来极大便利. 对于大公司来说,软件开发环境搭建工作一般是由运 ...

  7. Java 11 正式发布,这 8 个逆天新特性教你写出更牛逼的代码

    美国时间 09 月 25 日,Oralce 正式发布了 Java 11,这是据 Java 8 以后支持的首个长期版本. 为什么说是长期版本,看下面的官方发布的支持路线图表. 可以看出 Java 8 扩 ...

  8. c#代码 天气接口 一分钟搞懂你的博客为什么没人看 看完python这段爬虫代码,java流泪了c#沉默了 图片二进制转换与存入数据库相关 C#7.0--引用返回值和引用局部变量 JS直接调用C#后台方法(ajax调用) Linq To Json SqlServer 递归查询

    天气预报的程序.程序并不难. 看到这个需求第一个想法就是只要找到合适天气预报接口一切都是小意思,说干就干,立马跟学生沟通价格. ​ ​不过谈报价的过程中,差点没让我一口老血喷键盘上,话说我们程序猿的人 ...

  9. 一文深入了解史上最强的Java堆内缓存框架Caffeine

    它提供了一个近乎最佳的命中率.从性能上秒杀其他一堆进程内缓存框架,Spring5更是为了它放弃了使用多年的GuavaCache 缓存,在我们的日常开发中用的非常多,是我们应对各种性能问题支持高并发的一 ...

随机推荐

  1. python 常用知识点

    1,字典get用法 如果key没有值,返回一个None >>> dic = {'k1':'v1','k2':'v2','k3':'v3'} >>> dic.get( ...

  2. 1.2 eigen中矩阵和向量的运算

    1.2 矩阵和向量的运算 1.介绍 eigen给矩阵和向量的算术运算提供重载的c++算术运算符例如+,-,*或这一些点乘dot(),叉乘cross()等等.对于矩阵类(矩阵和向量,之后统称为矩阵 类) ...

  3. 简单了解下java中的堆、栈和方法区。

    堆.栈.方法区 1,首先了解下java中的数据类型. ①java中的八大基本数据类型:boolean, char , byte, short, int, long , float , double. ...

  4. 编译搭建lnmp+zabbix

    搭建nginx 1)基础依赖包安装 yum -y install gcc gcc-c++ vim tree make cmake autoconf yum -y install openssl ope ...

  5. vue全局路由守卫beforeEach

    在main.js里使用方法 router.beforeEach((to,from,next)=>{}) to,是将要跳转的路由, from,是离开的路由 next是个方法,判断to.path 或 ...

  6. 第42章:MongoDB-集群--Sharding(分片)--单机的搭建

    ①配置服务器 在大型的集群中,建议配置3台配置服务器,就足够用了.启动配置服务器的方式: 1:先创建几个存放数据的文件夹,比如在前面的dbs下面创建confdb文件夹,然后在confdb下面创建con ...

  7. python之路(二)-collections系列

    collections提供了一些比较方便的方法,使用时需要先导入模块 导入模块: import collections 1. 计数器Counter 统计参数中出现的次数,以字典的方式返回结果,参数可以 ...

  8. Centos7.0进入单用户模式修改root密码

    启动Centos7 ,按空格让其停留在如下界面. 按e进行编辑 在UTF-8后面输入init=/bin/sh 根据提示按ctrl+x 得如下图 输入mount -o remount,rw /  然后输 ...

  9. Hadoop 综合揭秘——HBase的原理与应用

    前言 现今互联网科技发展日新月异,大数据.云计算.人工智能等技术已经成为前瞻性产品,海量数据和超高并发让传统的 Web2.0 网站有点力不从心,暴露了很多难以克服的问题.为此,Google.Amazo ...

  10. Mybatis延迟加载、缓存

    一.Mybatis中的延迟加载 1.延迟加载背景:Mybatis中Mapper配置文件中的resultMap可以实现高级映射(使用association.collection实现一对一及一对多(多对多 ...