Skip to content

DSL

对象运算的dsl设计

Note

对象运算的简单DSL实现

设计思路

  • 基于栈做计算
  • 定义一元、运算符的运算逻辑

深入实践则进阶到 编译原理

Item<List<String>> result = ObjCalculatorDSL.of(
                Lists.newArrayList(
                        Item.<List<String>>of(List.of("a", "b", "c")),
                        Item.AND(),
                        Item.of(List.of("b", "c", "d")),
                        Item.OR(),
                        Item.of(List.of("c", "d", "e"))
                )
        )
        .AND(
                (l1, l2) -> {
                    if (Objects.isNull(l1) || l1.isEmpty()
                        || Objects.isNull(l2) || l2.isEmpty()
                    ) {
                        return Item.of(Lists.newArrayList());
                    }
                    Set<String> l2Set = new HashSet<>(l2);
                    return Item.of(
                            new HashSet<>(l1).stream()
                                    .filter(l2Set::contains)
                                    .toList(),
                            true);
                }
        )
        .OR(
                (l1, l2) -> {
                    if (Objects.isNull(l1) && Objects.isNull(l2)) {
                        return Item.of(Lists.newArrayList());
                    }
                    Set<String> l1Set = Objects.isNull(l1) ?
                            Sets.newHashSet() : new HashSet<>(l1);
                    Set<String> l2Set = Objects.isNull(l2) ?
                            Sets.newHashSet() : new HashSet<>(l2);
                    l1Set.addAll(l2Set);
                    return Item.of(l1Set.stream().distinct().toList(), true);
                }
        )
        .get();

Assertions.assertTrue(
        CollectionUtils.isEqualCollection(
                List.of("b", "c","d","e"),result.getData()
        )
);