English 中文(简体)
构建器模式中的重复
原标题:Repetition in Builder Pattern
  • 时间:2012-05-24 18:28:52
  •  标签:
  • java
  • dry

我使用建筑商模式(如Joshua Bloch s 有效爪哇 所解释的)做一些事情,其中特别令人烦恼的重复:

public class Foo {
    private String name;
    private int age;

    public static class Builder implements IBuilder {
        private String name;
        private int age;

        Builder name(String value) {
            name = value;
            return this;
        }

        Builder age(int value) {
            age = value;
            return this;
        }

        Foo build() {
           return new Foo(this);
        }
    }

    private Foo(Builder builder) {
        name = builder.name;
        age = builder.age;
    }
}

它很小,但很烦人。 我必须在每类中声明变量。 我尝试用字段创建一个类, 并扩展该类, 但我有错误 : 中有私人访问 。

是否有办法做到这一点,而不公布变数?

最佳回答

如果您的构建者纯粹是为了捕捉一帮州(而不是做任何中间计算), 您可以通过定义构建者界面来解答重复, 然后写入 Java 代理生成器 。

如果您要这样做, 您就不能依靠外部阶级 能够进入建筑工( 内部) 类的私人田地。 要围绕这个领域工作, 您也需要为每个字段定义访问器 。 例如 :

public class Foo {
  public interface Builder extends IBuilder {
    Builder name(String name);
    String name();

    Builder age(int age);
    int age();
    ...
  }

  public static Builder builder() {
    return BuilderFramework.newInstance(Builder.class);
  }

  public Foo(Builder builder) {
    ...
  }
}

或者,您的构建者可以在 < code> Map 或类似结构中暴露所有字段。 使用此路径, 您的界面只需要链条设置。 但是您放弃对您在构建者中的所有字段使用时间进行汇编时间检查 。 IMHO, 太大的折中 。

问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签