Builder模式和无限参数

时间:2014-08-21 07:43:05

标签: java oop instantiation builder

利用构建器模式我注意到在某些情况下,使用构建器方法传递无限参数一次更改多个值是理想的。

例如,假设我想做类似的事情:

public class Element {
    String name;
    Double fire, water, earth, air, dark, light;

    Element(Builder e) {
        name = e.name;
        fire = e.fire; water = e.water; earth = e.earth;
        air = e.air; dark = e.dark; light = e.light;
    }

    static class Builder {
        String name;
        // Default multipliers
        Double fire = 1.0, water = 1.0, earth = 1.0, air = 1.0, dark = 1.0, light = 1.0; 

        Builder(String name){ this.name = name; }

        public Builder setRes(Double... element) {
            for (int i = 0; i < element.length; i++) { element[i] = 0.5; }
            return this;
        }
        public Builder setVuln(Double... element) {
            for (int i = 0; i < element.length; i++) { element[i] = 2.0; }
            return this;
        }
        public Builder setImmune(Double... element) {
            for (int i = 0; i < element.length; i++) { element[i] = 0.0; }
            return this;
        }

        public Element create(){ return new Element(this); }
    }   
}

编译没有错误。这些类型只能包含0,0.5,1或2的确定值。给定多个“元素”,我想到的是每个'元素'必须创建3个方法,但问题是因此我的问题是实例化一个新元素 - 这将如何工作?它甚至是可能还是我坚持制作多种方法?

我问的原因是我看不出如何传递尚未初始化的实例的值。

直觉会让我(错误地)这样做

Element nora = new Element.Builder("Nora").setVuln(nora.dark, nora.light).create();

1 个答案:

答案 0 :(得分:2)

我可能会更改模型以使用Enum将元素类型的地图保存为乘数,并在构建元素时,将Enum字段传递给&#34;阻力&#34;,&# 34;漏洞&#34;和&#34;免疫力&#34;类似于以下内容:

public enum ElementType {

    DARK,
    LIGHT // ...
}

public class Element {
    String name;
    Map<ElementType, Double> multipliers = ...;

    // ...

    public Builder vulnerability(ElementType... elementTypes) {
        for (ElementType elementType : elementTypes) {
            multipliers.put(elementType , 2.0);
        }
        return this;
    }
}


Element nora = new Element.Builder("Nora").vulnerability(ElementType.DARK, ElementType.LIGHT).create();