【设计模式】JAVA Design Patterns——Combinator(功能模式)

简介: 【设计模式】JAVA Design Patterns——Combinator(功能模式)

🔍目的


功能模式代表了一种以组合功能为中心的图书馆组织风格。

简单地说,有一些类型 T,一些用于构造类型 T 的“原始”值的函数,以及一些可以以各种方式组合类型 T 的值以构建更复杂的类型 T 值的“组合器”


🔍解释


真实世界例子

在计算机科学中,组合逻辑被用作计算的简化模型,用于可计算性理论和证明理论。 尽管组合逻辑很简单,但它捕获了计算的许多基本特征。


通俗描述

组合器允许从先前定义的“事物”创建新的“事物”。


维基百科

组合器是一个高阶函数,仅使用函数应用程序和之前定义的组合器来定义其参数的结果。


程序实例

创建一个由notorandcontains方法组成的接口

// 用于查找文本中的行的功能界面。
public interface Finder {
 
  // 在文本中查找行的函数。
  List<String> find(String text);
 
  // 函数{@link #find(String)}的简单实现。
  static Finder contains(String word) {
        return txt -> Stream.of(txt.split("\n"))
            .filter(line -> line.toLowerCase().contains(word.toLowerCase()))
            .collect(Collectors.toList());
    }
 
  // 组合器:not。
  default Finder not(Finder notFinder) {
        return txt -> {
            List<String> res = this.find(txt);
            res.removeAll(notFinder.find(txt));
            return res;
          };
    }
 
  // 组合器:or。
  default Finder or(Finder orFinder) {
        return txt -> {
            List<String> res = this.find(txt);
            res.addAll(orFinder.find(txt));
            return res;
          };
  }
 
  // 组合器:and。
  default Finder and(Finder andFinder) {
        return
          txt -> this
                .find(txt)
                .stream()
                .flatMap(line -> andFinder.find(line).stream())
                .collect(Collectors.toList());
    }
  ...
}


另一个组合器用于一些复杂的查找器advancedFinder, filteredFinder, specializedFinderexpandedFinder

// 由简单取景器组成的复杂取景器。
public class Finders {
 
  private Finders() {
    }
 
  // Finder 用于查找复杂的查询。
  public static Finder advancedFinder(String query, String orQuery, String notQuery) {
        return
            Finder.contains(query)
                  .or(Finder.contains(orQuery))
                  .not(Finder.contains(notQuery));
  }
 
  // 过滤查找器也会查找包含排除查询的查询。
  public static Finder filteredFinder(String query, String... excludeQueries) {
    var finder = Finder.contains(query);
 
        for (String q : excludeQueries) {
            finder = finder.not(Finder.contains(q));
        }
        return finder;
  }
 
  // 专门查询。 每个下一个查询都会在上一个结果中查找。
  public static Finder specializedFinder(String... queries) {
        var finder = identMult();
 
    for (String query : queries) {
            finder = finder.and(Finder.contains(query));
        }
        return finder;
    }
 
  // 扩展查询。 寻找替代品。
  public static Finder expandedFinder(String... queries) {
        var finder = identSum();
 
        for (String query : queries) {
            finder = finder.or(Finder.contains(query));
        }
      return finder;
    }
  ...
}


创建一个处理这些组合器的应用程序

var queriesOr = new String[]{"many", "Annabel"};
var finder = Finders.expandedFinder(queriesOr);
var res = finder.find(text());
LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res);
 
var queriesAnd = new String[]{"Annabel", "my"};
finder = Finders.specializedFinder(queriesAnd);
res = finder.find(text());
LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res);
 
finder = Finders.advancedFinder("it was", "kingdom", "sea");
res = finder.find(text());
LOGGER.info("the result of advanced query is {}", res);
 
res = Finders.filteredFinder(" was ", "many", "child").find(text());
LOGGER.info("the result of filtered query is {}", res);
 
private static String text() {
    return
        "It was many and many a year ago,\n"
            + "In a kingdom by the sea,\n"
            + "That a maiden there lived whom you may know\n"
            + "By the name of ANNABEL LEE;\n"
            + "And this maiden she lived with no other thought\n"
            + "Than to love and be loved by me.\n"
            + "I was a child and she was a child,\n"
            + "In this kingdom by the sea;\n"
            + "But we loved with a love that was more than love-\n"
            + "I and my Annabel Lee;\n"
            + "With a love that the winged seraphs of heaven\n"
            + "Coveted her and me.";
  }


程序输出

the result of expanded(or) query[[many, Annabel]] is [It was many and many a year ago,, By the name of ANNABEL LEE;, I and my Annabel Lee;]
the result of specialized(and) query[[Annabel, my]] is [I and my Annabel Lee;]
the result of advanced query is [It was many and many a year ago,]
the result of filtered query is [But we loved with a love that was more than love-]


我们也可以设计我们的应用程序,使其具有查询查找功能expandedFinder, specializedFinder, advancedFinder, filteredFinder,这些功能均派生自contains, or, not, and


🔍类图


25189728830449b5a73ad50f4516ed8f.png


🔍适用场景


在以下情况下使用组合器模式:

  • 您可以从更简单的值创建更复杂的值,但具有相同的类型(它们的组合)


🔍优点


  • 从开发人员的角度来看,API 由领域中的术语组成。
  • 组合阶段和应用阶段之间有明显的区别。
  • 首先构造一个实例,然后执行它。
  • 这使得该模式适用于并行环境。

98897b136f3745c9a84e749c2aa24945.gif

相关文章
|
1天前
|
安全 Java API
深入解析 Java 8 新特性:LocalDate 的强大功能与实用技巧
深入解析 Java 8 新特性:LocalDate 的强大功能与实用技巧
8 1
|
1天前
|
Java API
深入探讨 Java 8 集合操作:全面解析 Stream API 的强大功能
深入探讨 Java 8 集合操作:全面解析 Stream API 的强大功能
9 2
|
1天前
|
设计模式 存储 安全
Java中的23种设计模式
Java中的23种设计模式
5 1
|
7天前
|
设计模式 新零售 Java
设计模式最佳套路5 —— 愉快地使用工厂方法模式
工厂模式一般配合策略模式一起使用,当系统中有多种产品(策略),且每种产品有多个实例时,此时适合使用工厂模式:每种产品对应的工厂提供该产品不同实例的创建功能,从而避免调用方和产品创建逻辑的耦合,完美符合迪米特法则(最少知道原则)。
29 6
|
7天前
|
设计模式 Java 关系型数据库
设计模式第2弹:工厂方法模式
type ComputerProduct struct{} // 实现工厂方法 func (computer ComputerProduct) GetInformation() string { return "电脑,官方称呼计算机,主要用于进行数据运算的一台机器。" }
22 4
|
7天前
|
设计模式 XML Java
【设计模式】第三篇:一篇搞定工厂模式【简单工厂、工厂方法模式、抽象工厂模式】
三 结尾 如果文章中有什么不足,欢迎大家留言交流,感谢朋友们的支持! 如果能帮到你的话,那就来关注我吧!如果您更喜欢微信文章的阅读方式,可以关注我的公众号
17 5
|
8天前
|
设计模式 架构师 NoSQL
设计模式-工厂方法模式和抽象工厂模式
 每增加一个产品就要增加一个具体产品类和一个对应的具体工厂类,这增加了系统的复杂度。
186 0
|
17天前
|
设计模式 存储 前端开发
Java的mvc设计模式在web开发中应用
Java的mvc设计模式在web开发中应用
|
17天前
|
存储 前端开发 Java
Java一分钟之-Java GUI设计原则与模式
本文介绍了Java GUI开发的核心设计原则和模式,包括分层架构(MVC)、组件复用、用户体验和代码示例。强调了MVC模式以提高代码可维护性,组件化设计以增强复用性,以及响应式和简洁界面以提升用户体验。同时,提出了常见问题的避免策略,如布局管理、资源释放和国际化支持,建议开发者遵循这些原则以提升GUI应用质量。
53 3
|
19天前
|
设计模式 安全 Java
【设计模式】JAVA Design Patterns——Curiously Recurring Template Pattern(奇异递归模板模式)
该文介绍了一种C++的编程技巧——奇异递归模板模式(CRTP),旨在让派生组件能继承基本组件的特定功能。通过示例展示了如何创建一个`Fighter`接口和`MmaFighter`类,其中`MmaFighter`及其子类如`MmaBantamweightFighter`和`MmaHeavyweightFighter`强制类型安全,确保相同重量级的拳手之间才能进行比赛。这种设计避免了不同重量级拳手间的错误匹配,编译时会报错。CRTP适用于处理类型冲突、参数化类方法和限制方法只对相同类型实例生效的情况。
【设计模式】JAVA Design Patterns——Curiously Recurring Template Pattern(奇异递归模板模式)