为了账号安全,请及时绑定邮箱和手机立即绑定

如何结合两个独立的 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 关注
  • 111 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号