是否可以在创建对象时使属性可选?

时间:2018-03-28 13:23:55

标签: java

好的,我有这个课程

public DBRestorerWorker(String dbName, Path fromFile, Path targetDataPath, Path targetLogPath,
        ProgressBar bar, Properties properties, Runnable done) {
    this.dbName = dbName;
    this.targetDataPath = targetDataPath;
    this.from = fromFile;
    this.targetLogPath = targetLogPath;
    this.bar = bar;
    this.properties = properties;
    this.done = done;
}

这个类在一个应用程序中使用,现在我正在创建它的瘦身版本所以我需要仍然使用这部分但是在瘦身版本中没有ProgressBar但我仍然需要创建这个类的对象所以因为老版本仍然需要它,所以有一些方法可以使ProgressBar成为可选项。

3 个答案:

答案 0 :(得分:5)

您可以添加一个新的构造函数,只需将null分配给ProgressBar字段:

public DBRestorerWorker(String dbName, Path fromFile, Path targetDataPath,
    Path targetLogPath, Properties properties, Runnable done) {

    DBRestorerWorker(dbName, fromFile, targetDataPath, targetLogPath, null,
        properties, done);
}

如果由于某种原因无法修改原始类,那么您仍然可以扩展以前的类并添加此构造函数。

答案 1 :(得分:2)

Builder pattern是你的油炸。

public final class DBRestorerWorker {

    private final String dbName;
    private final Path fromFile;
    private final Path targetDataPath;
    private final Path targetLogPath;
    private final ProgressBar bar;
    private final Properties properties;
    private final Runnable done;

    public static Builder builder() {
        return new Builder();
    }

    private DBRestorerWorker(Builder builder) {
        this.dbName = builder.dbName;
        // same for others
    }

    // getters

    public static final class Builder {
        private String dbName;
        private Path fromFile;
        private Path targetDataPath;
        private Path targetLogPath;
        private ProgressBar bar;
        private Properties properties;
        private Runnable done;

        private Builder() {
        }

        public Builder dbName(String dbName) {
            this.dbName = dbName;
            return this;
        }

        // same for other fields

        public DBRestorerWorker build() {
            return new DBRestorerWorker(this);
        }

    }
}

使用是这样的:

DBRestorerWorker worker = DBRestorerWorker.builder()
                                          .dbName("dbName")
                                          // other required fields
                                          .build();

P.S。 Lombok可以简化此模式的使用。

答案 2 :(得分:1)

现在你可以直接传递null。可选地,另外将参数标记为@Nullable。也许创建一个没有ProgressBar的第二个构造函数,它使用null来调用这个构造函数。

public DBRestorerWorker(String dbName, Path fromFile, Path targetDataPath, Path targetLogPath, Properties properties, Runnable done) {
    DBRestorerWorker(dbName, fromFile, targetDataPath, targetLogPath, null, properties, done)
}

并可选择@Nullable

public DBRestorerWorker(String dbName, Path fromFile, Path targetDataPath, Path targetLogPath, @Nullable ProgressBar bar, Properties properties, Runnable done) {
    // ...
}