使用场景:生成订单实体的时候,需要对价格,地址,商品等属性赋值
改造前
public static void main(String[] args) {
Order order = new Order() ;
System.out.println("处理收获地址业务逻辑");
order.setAccount("张三");
System.out.println("根据优惠券计算订单价格");
}
改造后
1. 对象的创建和属性赋值都通过接口来实现
public interface OrderBuilder{
public OrderBuilder setAccount(String account) ;
public OrderBuilder setAddress() ;
public OrderBuilder setPrice() ;
Order create();
}
2.实现接口
public class OrderBuilderImpl implements OrderBuilder{
private Order order = new Order() ;
@Override
public OrderBuilder setAddress() {
System.out.println("处理收获地址业务逻辑");
return this ;
}
@Override
public OrderBuilder setPrice() {
System.out.println("根据优惠券计算订单价格");
return this ;
}
@Override
public Order create() {
return order ;
}
}
?3.创建对象
public static void main(String[] args) {
OrderBuilder order = new OrderBuilderImpl()
.setAccount("张三")
.setAddress()
.setPrice()
.create() ;
}
|