亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何結合兩個獨立的 Java 構建器模式的代碼?

如何結合兩個獨立的 Java 構建器模式的代碼?

HUWWW 2023-03-23 16:29:06
我有一段代碼如下 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 產品上設置可用性,但沒有設置器,所以我必須創建 ProductBuilder 的實例,從產品復制值并設置可用性。如果產品為空或不為空并設置可用性字段,是否有更簡潔的方法來執行此操作?
查看完整描述

1 回答

?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

如果您在該字段上沒有設置器,一個好的方法是在您的構建器中添加一個方法,該方法將“產品”作為參數。


然后你可以這樣做:


   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())

   }


查看完整回答
反對 回復 2023-03-23
  • 1 回答
  • 0 關注
  • 92 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號