一、建造者模式
建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
二、代码实例
1、OrderItem类
@Data:这是Lombok中提供的Getter和Setter方法和toString方法的注解
@AllArgsConstructor:这是Lombok中提供的包含所有参数的构造方法注解
@NoArgsConstructor:这是Lombok中提供的不包含任何参数的构造方法注解
package com.xu.demo.builderPattern;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
// 订单项对象
public class OrderItem {private String productCode;private int quantity;
}
2、Order类
package com.xu.demo.builderPattern;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.List;// 订单对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {private String orderNumber;private List<OrderItem> orderItems;private String shippingAddress;private String paymentInfo;}
3、OrderBuilder类
package com.xu.demo.builderPattern;import java.util.ArrayList;// 订单建造者
public class OrderBuilder {private Order order;public OrderBuilder() {this.order = new Order();}public OrderBuilder setOrderNumber(String orderNumber) {order.setOrderNumber(orderNumber);return this;}public OrderBuilder addOrderItem(String productCode, int quantity) {if (order.getOrderItems() == null) {order.setOrderItems(new ArrayList<>());}order.getOrderItems().add(new OrderItem(productCode, quantity));return this;}public OrderBuilder setShippingAddress(String shippingAddress) {order.setShippingAddress(shippingAddress);return this;}public OrderBuilder setPaymentInfo(String paymentInfo) {order.setPaymentInfo(paymentInfo);return this;}public Order build() {return order;}
}
4、BuilderPattern
package com.xu.demo.builderPattern;/*** 建造者模式测试类*/
public class BuilderPattern {public static void main(String[] args) {// 使用建造者构建订单Order order = new OrderBuilder().setOrderNumber("123456").addOrderItem("汉堡", 2).addOrderItem("可乐", 1).setShippingAddress("天府大道001号").setPaymentInfo("花呗").build();// 打印订单信息System.out.println("订单编号: " + order.getOrderNumber());System.out.println("送货地址: " + order.getShippingAddress());System.out.println("支付方式: " + order.getPaymentInfo());System.out.println("订单商品列表: " + order.getOrderItems());}
}
运行结果如下: