Java中有没有办法实现这样的目标:
jPanel1.label1
.setText("something")
.setEnabled(something)
.setVisible(something)
而不是一遍又一遍地输入相同的变量名?谢谢!
答案 0 :(得分:1)
是。按照builder pattern
来实现您的目标。它的每个方法在修改后返回相同的实例。
直接粘贴示例:
public class StreetMap {
private final Point origin;
private final Point destination;
private final Color waterColor;
private final Color landColor;
private final Color highTrafficColor;
private final Color mediumTrafficColor;
private final Color lowTrafficColor;
public static class Builder {
// Required parameters
private final Point origin;
private final Point destination;
// Optional parameters - initialize with default values
private Color waterColor = Color.BLUE;
private Color landColor = new Color(30, 30, 30);
private Color highTrafficColor = Color.RED;
private Color mediumTrafficColor = Color.YELLOW;
private Color lowTrafficColor = Color.GREEN;
public Builder(Point origin, Point destination) {
this.origin = origin;
this.destination = destination;
}
public Builder waterColor(Color color) {
waterColor = color;
return this;
}
public Builder landColor(Color color) {
landColor = color;
return this;
}
public Builder highTrafficColor(Color color) {
highTrafficColor = color;
return this;
}
public Builder mediumTrafficColor(Color color) {
mediumTrafficColor = color;
return this;
}
public Builder lowTrafficColor(Color color) {
lowTrafficColor = color;
return this;
}
public StreetMap build() {
return new StreetMap(this);
}
}
private StreetMap(Builder builder) {
// Required parameters
origin = builder.origin;
destination = builder.destination;
// Optional parameters
waterColor = builder.waterColor;
landColor = builder.landColor;
highTrafficColor = builder.highTrafficColor;
mediumTrafficColor = builder.mediumTrafficColor;
lowTrafficColor = builder.lowTrafficColor;
}
public static void main(String args[]) {
StreetMap map = new StreetMap.Builder(new Point(50, 50), new Point(100,
100)).landColor(Color.GRAY).waterColor(Color.BLUE.brighter())
.build();
}
}