【问题标题】:how to eliminate duplicate code in initmethod如何消除initmethod中的重复代码
【发布时间】:2018-08-25 08:50:19
【问题描述】:

我有类 Dog, Cat, ... 扩展 Pet 和 init 方法。如果init方法必须为void,如何消除重复代码。

public class Tester {
    private Pet pet1;
    private Pet pet2;
    private int i;

    public void pet1Init(){
        switch (i){
            case 0:
                pet1 = new Cat();
                break;
            case 1:
                pet1 = new Dog();
                break;
            .....
        }
    }

    public void pet2Init(){
        switch (i){
            case 0:
                pet2 = new Cat();
                break;
            case 1:
                pet2 = new Dog();
                break;
            .......
        }
    }
}

【问题讨论】:

  • 你可以添加一个private static Pet create(int i) { ... } 方法。
  • @BenWatson,以及如何初始化 pet1pet2(如果它们作为参数传递)?
  • @BenWatson Java 是 pass by value。因此,您不能通过将参数传递给方法来初始化参数。

标签: java code-duplication


【解决方案1】:

我会给你一个不改变你的设计的解决方案,看看它有多尴尬:

public void pet1Init(){
    pet1 = getPet().get();
}

public void pet2Init(){
    pet2 = getPet().get();
}

private Supplier<Pet> getPet() {
    Supplier<Pet> supplier = Cat::new; // default pet

    switch (i){
        case 0:
            supplier = Cat::new;
            break;
        case 1:
            supplier = Dog::new;
            break;
    }

    return supplier;
}

更清洁的解决方案使用Map&lt;Integer, Supplier&lt;Pet&gt;&gt;:

private Map<Integer, Supplier<Pet>> map = Map.of(0, Cat::new, 1, Dog::new);

private Supplier<Pet> getPet() {
    return map.getOrDefault(i, Cat::new);
}

不过,目前还不清楚您要达到的目标。这些变量可以在单个方法中初始化,因为它们共享相同的算法:

public void initialisePets(){
    final Supplier<Pet> supplier = getPet();

    pet1 = supplier.get();
    pet2 = supplier.get();
}

【讨论】:

    猜你喜欢
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多