• 欢迎光临~

设计模式之建造者模式-案例代码

开发技术 开发技术 2022-10-06 次浏览

1、类图

设计模式之建造者模式-案例代码

 

 

 2、代码实例

public abstract class ConditionBuilder {

    public abstract void buildOrderId();

    public abstract void buildOrderType();

    public abstract SearchCondition getResult();
}


public class SearchCondition {

private String orderId;

private Integer orderType;

public String getOrderId() {
return orderId;
}

public void setOrderId(String orderId) {
this.orderId = orderId;
}

public Integer getOrderType() {
return orderType;
}

public void setOrderType(Integer orderType) {
this.orderType = orderType;
}

public String showSearchCondition(){
return "SearchCondition{" +
"orderId='" + orderId + ''' +
", orderType=" + orderType +
'}';
}
}



public class SearchConditionBuilder extends ConditionBuilder{

private SearchCondition searchCondition = new SearchCondition();

private Map<String,Object> reqParams;

public SearchConditionBuilder(Map<String, Object> reqParams) {
if(reqParams!=null){
this.reqParams = reqParams;
}else{
this.reqParams= new HashMap<>();
}

}

@Override
public void buildOrderId() {
searchCondition.setOrderId(reqParams.get("orderId")!=null?(String)reqParams.get("orderId"):null);
}

@Override
public void buildOrderType() {
searchCondition.setOrderType(reqParams.get("orderType")!=null?(Integer) reqParams.get("orderType"):null);
}

@Override
public SearchCondition getResult() {
return searchCondition;
}
}



public class ConditionDirector {

public void constructCondition(ConditionBuilder conditionBuilder){
conditionBuilder.buildOrderId();
conditionBuilder.buildOrderType();
}
}


测试代码main():
public class TestBuilder {

public static void main(String[] args) {
ConditionDirector conditionDirector = new ConditionDirector();

Map<String,Object> reqParams= new HashMap<>();
reqParams.put("orderId","123456");
reqParams.put("orderType",0);

SearchConditionBuilder searchConditionBuilder = new SearchConditionBuilder(reqParams);
conditionDirector.constructCondition(searchConditionBuilder);

SearchCondition result = searchConditionBuilder.getResult();
System.out.println(result.showSearchCondition());

}
}

 

 

 

程序员灯塔
转载请注明原文链接:设计模式之建造者模式-案例代码
喜欢 (0)