這篇文章給大家介紹Builder模式如何在Java中實現(xiàn),內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
10年積累的成都做網(wǎng)站、網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設經(jīng)驗,可以快速應對客戶對網(wǎng)站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡服務。我雖然不認識你,你也不認識我。但先網(wǎng)站設計制作后付款的網(wǎng)站建設流程,更有阿拉山口免費網(wǎng)站建設讓你可以放心的選擇與我們合作。Pre Java8
我們先來看下在Java8之前的Builder模式
public class Order { private String code; private Listoffers; private Map 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 features; private List offers; //省略getter setter } public Builder code(String code) { orderState.code = code; return this; } public Builder features(Map features) { orderState.features = features; return this; } public 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 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; } } }