这篇文章给大家介绍Builder模式如何在Java中实现,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。Pre Java8我们先来看下在Java8之前的Builder模式public class Order { priv
这篇文章给大家介绍Builder模式如何在Java中实现,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
Pre Java8
我们先来看下在Java8之前的Builder模式
public class Order { private String code; private List<String> offers; private Map<String, Object> features; public static Order.Builder builder(){ return new Builder(); } //省略getter setter public static class Builder { private OrderState orderState = new OrderState(); private static final BeanCopier orderCopier = BeanCopier.create(OrderState.class, Order1.class, false); private class OrderState { private String code; private Map<String, Object> features; private List<String> offers; //省略getter setter } public Builder code(String code) { orderState.code = code; return this; } public Builder features(Map<String, Object> features) { orderState.features = features; return this; } public <T> Builder feature(String key, T obj) { if (orderState.features == null) { orderState.features = new HashMap<>(); } orderState.features.put(key, obj); return this; } public Builder offers(List<String> offers) { orderState.offers = offers; return this; } public Builder offer(String offer) { if (orderState.offers == null) { orderState.offers = new ArrayList<>(); } orderState.offers.add(offer); return this; } public Order build() { Order order = new Order(); orderCopier.copy(orderState, order1, null); orderState = null; return order; } }}
--结束END--
本文标题: Builder模式如何在Java中实现
本文链接: https://lsjlt.com/news/226460.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0