java 多条件构造函数_如何为不同类型的可变数量的参数编写Java构造函数?

这可能适用于建造者模式

public class Stamp {

public static class Builder {

// default values

private String code = "default code"

private int year = 1900;

// etc.

public Builder withCode(String code) {

this.code = code;

return this;

}

public Builder withYear(int year) {

this.year = year;

return this;

}

// etc.

public Stamp build() {

return new Stamp(code, year, country, value, numberOfCopies);

}

}

public Stamp(String code, int year, String country, double value,

int numberOfCopies){...}

}

然后,施工过程变为

Stamp s = new Stamp.Builder()

.withCode("some_code")

.withYear(1991)

.build();

这样,参数不再依赖于顺序 – 您可以等效地说

Stamp s = new Stamp.Builder()

.withYear(1991)

.withCode("some_code")

.build();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值