gpt4 book ai didi

java - 重构:删除构造函数中的重复项

转载 作者:行者123 更新时间:2023-12-05 09:37:09 27 4
gpt4 key购买 nike

我似乎缺乏足够的咖啡来让我清楚地看到以下问题。

假设我有一个包含两个构造函数和多个字段的类。一个构造函数是无参数构造函数,一个字段依赖于另一个字段。另一个构造函数为其其中一个字段获取注入(inject)值。示例:

public class Practice {
private final int n;
private final char c;
private final Map<String, String> m;
private final Set<String> s;

public Practice() {
this.n = 0;
this.c = 'a';
this.m = new HashMap<>();
this.s = m.keySet();
}

public Practice(Set<String> s) {
this.n = 0;
this.c = 'a';
this.m = new HashMap<>();
this.s = s;
}
}

我的问题:如何删除两个构造函数之间的重复代码?

第一次失败的尝试:

public Practice() {
this(new HashMap<>(), new HashMap<>().keySet());
}

public Practice(Set<String> s) {
this(new HashMap<>(), s);
}

private Practice(int n, char c, Map<String, String> m, Set<String> s) {
this.n = 0;
this.c = 'a';
this.m = m;
this.s = s;
}

当然,这会失败,因为无参数构造函数创建了两个独立的 Map 而不是一个。

最佳答案

如果一个参数依赖于另一个参数,您可以通过添加额外的构造函数来解决问题。在这种情况下 private Practice(Map<String,String> map)

public Practice() {
this(new HashMap<>());
}

public Practice(Set<String> s) {
this(new HashMap<>(), s);
}

private Practice(Map<String,String> map) {
this(map, map.keySet());
}

private Practice(Map<String,String> map, Set<String> s) {
this.n = 0;
this.c = 'a';
this.m = map;
this.s = s;
}

关于java - 重构:删除构造函数中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64557928/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com