如何创建一个不可变的建设者不可变的类,包含一套? [英] How to create an immutable builder of an immutable class that contains a set?

查看:136
本文介绍了如何创建一个不可变的建设者不可变的类,包含一套?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个包含一个Set的不可变类的不可变构造器。它应该是一个不可变的集合,但现在我必须使用常规的JCF类。使用标准比萨饼样本,我有比萨饼基地作为必需参数,浇头可选,0或更多允许。我想像,每次调用 addToppings()将创建一个新的不可变的构建器,一组浇头,然后最后,当构建被称为比萨对象将被传递。我只是不知道如何建立不变的一套 toppings 。这是我的代码:

I am trying to create an immutable builder of an immutable class that contains a Set. It should be an immutable set really but for now I have to use the regular JCF classes. Using the standard pizza example, I have the pizza base as a mandatory parameter and toppings as optional, 0 or more allowed. I imagine that each call to addToppings() will create a new immutable builder with a set of toppings and then finally when build is called the Pizza object will be delivered. I just don't know how to build up the immutable set of toppings. Here is my code:

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;

}

我知道这是一个偏离'标准'新建构件模式,但是我发现存储和复制的值存在偏差,因为目标类已经定义了需要哪些字段。

I know this is a deviation from the 'standard' new builder pattern but I find the storing and copying of values there inelegant because the target class already defines what fields are needed.

推荐答案

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来维护浇头的顺序。

Is that what you're interested in? I chose LinkedHashSet to maintain the order of the toppings.

这篇关于如何创建一个不可变的建设者不可变的类,包含一套?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆