建造者模式:将构建一个复杂的对象与它的表示分离,使得同样的构建构建过程可以有不同的表示。
1、类图
2、实现
public abstract class AbstractExport {
protected String type;
protected String name;
public abstract void buildType();
public abstract void buildName();
public final void build() {
buildType();
buildName();
System.out.println("type:" + this.type);
System.out.println("name:" + this.name);
}
}
public class AsyncExport extends AbstractExport {
@Override
public void buildType() {
super.type = "async type";
}
@Override
public void buildName() {
super.name = "async name";
}
}
public class SyncExport extends AbstractExport {
@Override
public void buildType() {
super.type = "sync type";
}
@Override
public void buildName() {
super.name = "sync name";
}
}
public class ExportTest {
public static void main(String[] args) {
AsyncExport asyncExport = new AsyncExport();
asyncExport.buildName();
asyncExport.buildType();
asyncExport.build();
}
}
3、实际使用
public class BaseCode {
private static final long serialVersionUID = 1L;
private String code;
private Long type;
public static BaseCode.BaseCodeBuilder builder() {
return new BaseCode.BaseCodeBuilder();
}
public BaseCode(String code, Long type) {
this.code = code;
this.type = type;
}
public BaseCode() {
}
public String getCode() {
return this.code;
}
public Long getType() {
return this.type;
}
public void setCode(String code) {
this.code = code;
}
public void setType(Long type) {
this.type = type;
}
public static class BaseCodeBuilder {
private String code;
private Long type;
BaseCodeBuilder() {
}
public BaseCode.BaseCodeBuilder code(String code) {
this.code = code;
return this;
}
public BaseCode.BaseCodeBuilder type(Long type) {
this.type = type;
return this;
}
public BaseCode build() {
return new BaseCode(this.code, this.type);
}
public String toString() {
return "BaseCode.BaseCodeBuilder(code=" + this.code + ", type=" + this.type + ")";
}
}
}
4、lombok中的建造者模式
使用:@Builder
@Builder
public class BaseCode {
private static final long serialVersionUID = 1L;
/**
* <pre>
* 编码
* </pre>
*
*/
private String code;
/**
* <pre>
* 编码类型:1:BOSS;2:VIP
* </pre>
*
*/
private Long type;
}