听起来您可能需要一些“默认参数”。在 Python 中,您可以执行以下操作:
class MyClass:
def __init__(done=false, load=1, ...):
self.done = done
self.load = load
# ...
a_new_instance = MyClass(done=true)
基本上,您的所有变量都以默认值开始 -但如果您愿意,可以更改它们。
在 Java 中,它有点不同:
class MyClass {
private boolean done = false; // Notice the default value for done will be false
// ... you would list (and instantiate!) the rest of your variables
public MyClass() {}
public MyClass(boolean done, int lvl, ...) {
this.done = done;
// ...
}
}
这样,如果您想更改默认值,您只需要调用构造函数。但是,如果您只想更改 1 或 2 个值会发生什么?好吧,您可以创建新的构造函数:
public MyClass(boolean done) { this.done = done; }
public MyClass(boolean done, int lvl) { this.done = done; this.lvl = lvl; }
但这很快就会失控!
所以,为了解决这个问题,我们可以使用“builder”模式。这看起来像这样:
public class MyClass {
private boolean done;
private int lvl;
// Now the constructor is private and takes a builder.
private MyClass(MyClassBuilder builder) {
// ... and your variables come from the ones you will build.
this.done = builder.done;
this.lvl = builder.lvl;
// ...
}
public static class MyClassBuilder {
// The builder also has the same members.
private boolean done;
private int lvl;
// Notice that we return the builder, this allows us to chain calls.
public MyClassBuilder done(boolean isDone) {
this.done = isDone;
return this;
}
public MyClassBuilder level(int level) {
this.lvl = level;
}
// And a method to build the object.
public MyClass build() {
MyClass mc = new MyClass();
mc.done = this.done;
mc.lvl = this.lvl;
// ... copy over all your variables from the builder to the new class
return mc;
}
}
}
所以,现在当我们想要实例化一个MyClass
对象时,我们可以这样做:
MyClass mc = MyClassBuilder.done(false);
或者,我们可以链接调用:
MyClass mc2 = MyClassBuilder.done(true).level(4). // ... you can go on for a while
顺便说一句,有时一个类中包含三个或四个以上的变量表明该类做得太多。如果班级有多个“职责”,则应将其分成几个较小的班级。那么您将不需要构建器类。