【问题标题】:How to implement a checked builder pattern in Java如何在 Java 中实现检查构建器模式
【发布时间】:2020-04-29 20:01:57
【问题描述】:

我正在尝试实现类似于以下描述的检查构建器模式: https://dev.to/schreiber_chris/creating-complex-objects-using-checked-builder-pattern

我试图达到的结果如下:

Builder builder = new Builder('TestVal')
    .when('this').then(new Set<String> {'val1','val2'})
    .when('that').then(new Set<String> {'val3','val4'});

结果对象将包含一个集合,其中包含任意数量的 whens 以及相关联的 thens 例如像这样的地图(when() 的参数是唯一的):

'this' => ['val1','val2'],
'that' => ['val3','val4']

我正在为几件事苦苦挣扎:

  1. 如何将传入then() 的值与值相关联 传入when()
  2. 如何要求 then() 被调用后 when()。 (例如 - .when('this').when('that') //invalid

【问题讨论】:

    标签: java design-patterns method-chaining builder-pattern


    【解决方案1】:

    最简单的方法是使用多个接口来强制执行您的调用排序,然后使用这些知识来关联您的项目。例如,大致如下:

    interface Then{
        When then(Set<String> values);
    }
    
    interface When{
        Then when(String condition);
    }
    
    class Builder implements When, Then{
    
        public static When create(){ return new Builder(); }
    
        private Map<String, Set<String>> storedMappings = new HashMap<>();
        private String currentCondition;
    
        private Builder(){ }
    
        public Then when(String condition){
            currentCondition = condition;
            return this;
        }
    
        public When then(Set<String> values){
            storedMappings.put(currentCondition, values);
            return this;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多