我有有25个字段的实体。它没有任何逻辑,只是存储价值。它是用抽象的构建器构建的。我不想在建造后改变这个实体。我想使所有字段都是最终的,但我不希望使25-params构造函数。在这种情况下我应该使用什么模式?现在我想到了包本地设置程序,但它比最后字段中所有值设置的语法检查更糟糕。我不能将这些字段打包到2-3个对象中。
发布于 2013-09-17 17:25:09
我认为有三个主要选择:
发布于 2013-09-17 17:34:13
将Builder类作为static嵌套类放在Entity类中。然后,Builder类可以直接设置字段,您不需要在Entity中使用setter方法或need构造函数。
public class Entity
{
// Just one attribute and getter here; could be 25.
private int data;
public int getData() { return data; }
public static class Builder
{
// Just one attribute and getter here; could be 25.
private int theData;
public Entity build()
{
Entity entity = new Entity();
// Set private field(s) here.
entity.data = theData;
return entity;
}
public Builder setData(int someData)
{
theData = someData;
return this;
}
}
}用法:
Entity entity = new Entity.Builder().setData(42).build();https://stackoverflow.com/questions/18856059
复制相似问题