我有一段代碼如下 private Product createProduct(ProductParmas params){ Product product = repository.getProduct(id) ProductBuilder.Builder builder = new ProductBuilder.Builder(); // this is a product builder if(product == null){ builder.location("abc").quantity(5).price(10) if(parmas.getAvaiability() != null){ builder.availability(parmas.getAvaiability()) } } // I also want to set Availability on obj product, but there are no setters so I have to create an instance of ProductBuilder, copy values from product and also set availability. Is there a cleaner way to come both if product is null or not null and set availability field?}我還想在 obj 產(chǎn)品上設(shè)置可用性,但沒(méi)有設(shè)置器,所以我必須創(chuàng)建 ProductBuilder 的實(shí)例,從產(chǎn)品復(fù)制值并設(shè)置可用性。如果產(chǎn)品為空或不為空并設(shè)置可用性字段,是否有更簡(jiǎn)潔的方法來(lái)執(zhí)行此操作?
1 回答

吃雞游戲
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果您在該字段上沒(méi)有設(shè)置器,一個(gè)好的方法是在您的構(gòu)建器中添加一個(gè)方法,該方法將“產(chǎn)品”作為參數(shù)。
然后你可以這樣做:
Product product = repository.getProduct(id)
ProductBuilder.Builder builder = new ProductBuilder.Builder()
if(product == null){
builder.location("abc").quantity(5).price(10)
if(parmas.getAvaiability() != null){
builder.availability(parmas.getAvaiability())
}
} else {
builder.withProduct(product)
.availability(params.getAvailability())
}
添加回答
舉報(bào)
0/150
提交
取消