设计模式之构建者模式
构建者模式:
一、什么是构建者模式
将构建的过程和表示的过程进行分离;
使用场景:
创建一个复杂的对象,同时该复杂对象有很多的默认值(初始化)的时候,可以使用构建者模式(给对象设置可选参数);
二、支付代码如下:
package com.anan.builder.demo1;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Charges {
private Builder builder;
public Charges(Builder builder) {
this.builder = builder;
}
public void Pay(){
System.out.println("去支付");
System.out.println("支付信息"+this.builder.params.id);
System.out.println("支付信息"+this.builder.params.body);
}
/**
* 参数类
*/
private static class ChargesParams {
String id;
String crete;
String channel;
String orderId;
String amount;
String clienIp;
String body;
}
/**
* 构建类
*/
public static class Builder {
private ChargesParams params;
public Builder() {
this.params = new ChargesParams();
this.params.id="10101010";
this.params.channel="通道";
this.params.orderId="orderId";
this.params.body="支付商品详情";
this.params.clienIp="192.168.12";
}
public Builder id(String id) {
this.params.id = id;
return this;
}
public Builder crete(String crete) {
this.params.crete = crete;
return this;
}
public Builder channel(String channel) {
this.params.channel = channel;
return this;
}
public Builder orderId(String orderId) {
this.params.orderId = orderId;
return this;
}
public Builder amount(String amount) {
this.params.amount = amount;
return this;
}
public Builder clienIp(String clienIp) {
this.params.clienIp = clienIp;
return this;
}
public Builder body(String body) {
this.params.body = body;
return this;
}
/**
* 数据处理完毕之后处理逻辑放在构造函数里面
*
* @return
*/
public Charges builder() {
return new Charges(this);
}
}
}
主方法的使用:
Charges charges = new Charges.Builder().crete("2017").body("支付宝支付")
.amount("300").builder();
charges.Pay();
或者
new Charges.Builder()
.crete("2017")
.body("支付宝支付")
.amount("300")
.builder()
.Pay();
三、分析构建者里面的角色:
角色一:产品ChargesParams也就是对象的属性;
角色二:抽象构建者(抽出相同的方法);(可以忽略)
角色三:具体的构建者Builder
角色四:组装(即调用的方法)
Ps: 角色一和角色三是必须有的,其他可以忽略;

浙公网安备 33010602011771号