|
| 1 | +package io.github.hooj0.builder.support.simple; |
| 2 | + |
| 3 | +/** |
| 4 | + * simple example, product entity class |
| 5 | + * Product的构造使用了Builder,造成了紧耦合,也说明Product需要Builder才能构造对象实例 |
| 6 | + * @author hoojo |
| 7 | + * @createDate 2018年10月14日 下午10:42:32 |
| 8 | + * @file Product.java |
| 9 | + * @package io.github.hooj0.builder.support.simple |
| 10 | + * @project design-patterns |
| 11 | + * @blog http://hoojo.cnblogs.com |
| 12 | + |
| 13 | + * @version 1.0 |
| 14 | + */ |
| 15 | +public final class Product { |
| 16 | + |
| 17 | + private final String name; |
| 18 | + private final float price; |
| 19 | + private final int size; |
| 20 | + private final String orderNo; |
| 21 | + |
| 22 | + private Product(Builder builder) { |
| 23 | + |
| 24 | + this.name = builder.name; |
| 25 | + this.price = builder.price; |
| 26 | + this.size = builder.size; |
| 27 | + this.orderNo = builder.orderNo; |
| 28 | + } |
| 29 | + |
| 30 | + public String getName() { |
| 31 | + return name; |
| 32 | + } |
| 33 | + |
| 34 | + public float getPrice() { |
| 35 | + return price; |
| 36 | + } |
| 37 | + |
| 38 | + public int getSize() { |
| 39 | + return size; |
| 40 | + } |
| 41 | + |
| 42 | + public String getOrderNo() { |
| 43 | + return orderNo; |
| 44 | + } |
| 45 | + |
| 46 | + public static final class Builder { |
| 47 | + private final String name; |
| 48 | + private float price; |
| 49 | + private int size; |
| 50 | + private String orderNo; |
| 51 | + |
| 52 | + public Builder(String name) { |
| 53 | + if (name == null) { |
| 54 | + throw new IllegalArgumentException("name can not be null"); |
| 55 | + } |
| 56 | + this.name = name; |
| 57 | + } |
| 58 | + |
| 59 | + public Builder price(float price) { |
| 60 | + this.price = price; |
| 61 | + |
| 62 | + return this; |
| 63 | + } |
| 64 | + |
| 65 | + public Builder size(int size) { |
| 66 | + this.size = size; |
| 67 | + |
| 68 | + return this; |
| 69 | + } |
| 70 | + |
| 71 | + public Builder orderNo(String orderNo) { |
| 72 | + this.orderNo = orderNo; |
| 73 | + |
| 74 | + return this; |
| 75 | + } |
| 76 | + |
| 77 | + public Product build() { |
| 78 | + |
| 79 | + if (this.size <= 0) { |
| 80 | + throw new IllegalArgumentException("size can not be zore."); |
| 81 | + } |
| 82 | + |
| 83 | + return new Product(this); |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments