我刚开始从Wiki学习和实现构建器模式。还有效Java的CH2。
这与JSP servlet有关,这可能有点令人费解,但我只是想让你们通过这个来看看如何正确地做到这一点。
让我们从一个场景开始,你不能完全构建对象,但是没有给出某些信息。因此,您很可能必须将对象放入会话中,然后再将变量添加到会话对象中。我如何使用Build模式实现这一目标?
这是一个代码示例
public class Widget(){
public static class Builder(){
public Builder(String id) {...}
public Builder serialNumber (String val) {...}
public Builder area (String val) {...}
public Widget build() { return new Widget(this); }
}
private Widget(Builder builder){...}
}
JSP Servlet 1 //只有ID信息
Widget w = new Widget().Builder(id).build();
HttpSession session = request.getSession();
session.setAttribute("widget", w);
JSP Servlet 2 //现在我有序列和区域
Widget.Builder w = (Widget.Builder) session.getAttribute("widget");
//** This is as far as I go **
w.serialNumber("something") // Now this works
.area("sideArea") //
.build() // < I know if I do this I will be creating another Object. Is there a way to use build pattern without creating redundant obj?
谢谢大家...
答案 0 :(得分:1)
w.serialNumber("something") // Can not find symbol
因为serialNumber不是w对象的方法。您可能正在寻找的是method chaining:
public class Widget {
... //assuming you have all the right fields here
public Widget setSerialNumber(String id) {
this.id = id;
return this;
}
public Widget setArea(String area) {
this.area = area;
return this;
}
public static class Builder(){
public Builder(String id) {...}
public Builder serialNumber (String val) {...}
public Builder area (String val) {...}
public Widget build() { return new Widget(this); }
}
private Widget(Builder builder){...}
}
然后你可以这样做:
w.setSerialNumber(id).setArea(area);
如果要构建新的Widget对象,请使用Widget.Builder;如果要更改现有的Widget对象,请使用方法链接。