我试图创建一个包含Set的不可变类的不可变生成器。它确实应该是一个不可变的集合,但是现在我必须使用常规的JCF类。以标准的披萨示例为例,我将披萨基数作为必填参数,将浇头作为可选参数,允许0或更大。我想每次调用addToppings()都会创建一个带有一组浇头的新的不可变生成器,然后最终在调用build时将发送Pizza对象。我只是不知道如何建立不可变的toppings集。这是我的代码:

public class Pizza {

private Pizza(Base base, Set<Topping> toppings) {
    this.base = base;
    this.toppings = toppings;
}

public static PizzaBuilder createBuilder(Base pizzaBase) {
    return new PizzaBuilder(new Pizza(pizzaBase, null));
}

public static class PizzaBuilder {
    private PizzaBuilder(Pizza pizza) {
        this.pizza = pizza;
    }

    public PizzaBuilder addTopping(Topping topping) {
        return new PizzaBuilder(new Pizza(pizza.base, ???));
    }

    public Pizza build() {
        return pizza;
    }

    final private Pizza pizza;
}

public Collection<Topping> getToppings() {
    return Collections.unmodifiableSet(toppings);
}

enum Base {DEEP_PAN, THIN}
enum Topping {MOZZARELLA, TOMATO, ANCHOVIES, PEPPERONI}

final private Base base;
final private Set<Topping> toppings;


}

我知道这与“标准”新的构建器模式有所不同,但是我发现其中的值存储和复制不佳,因为目标类已经定义了需要哪些字段。

最佳答案

public PizzaBuilder addTopping(Topping topping) {
    Set<Topping> toppings = null;
    if (pizza.toppings == null)
        toppings = new LinkedHashSet<Topping>();
    else
        toppings = new LinkedHashSet<Topping>(pizza.toppings);
    toppings.add(topping);
    return new PizzaBuilder(new Pizza(pizza.base, toppings));
}


这就是您感兴趣的吗?我选择LinkedHashSet来保持浇头的顺序。

关于java - 如何创建包含集合的不可变类的不可变生成器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5396534/

10-10 07:31