最近工作中需要写个小程序来填充邮件的内容,由于邮件内容需要支持表格等样式,为了避免直接拼写纯 HTML 代码,所以自己写了个 HtmlWrapper.java
对拼接 HTML 的过程进行包装。以便减少拼装过程中的代码冗余。于是便有了个分享 Builder 模式的想法。
对于 构建者模式 的使用场景,以及优缺点等说明,请参考 菜鸟教程|建造者模式 ,这边文章里面已经说明的非常详细和清楚了。
HtmlWrapper.java
的 Builder 实现:
public class HtmlWrapper {
private String tag;
private String content;
private String attrsInTag;
// We don't want client side to initialize a `HtmlWrapper`, so we make the construct method as `private`
private HtmlWrapper(Builder builder) {
this.tag = builder.getTag();
this.content = builder.getContent();
this.attrsInTag = builder.getAttrsInTag();
}
// `Builder` is a common name in Builder Pattern, you can give a name what ever you want, but `Builder` is the best
public static class Builder {
private String tag;
private String content;
private String attrsInTag;
private String getTag() {
return tag;
}
public Builder setTag(String tag) {
this.tag = tag;
return this;
}
private String getContent() {
return content;
}
public Builder setContent(String content) {
this.content = content;
return this;
}
private String getAttrsInTag() {
return attrsInTag;
}
public Builder setAttrsInTag(String attrsInTag) {
this.attrsInTag = attrsInTag;
return this;
}
public HtmlWrapper build() {
return new HtmlWrapper(this);
}
}
}
下面是客户端调用 HtmlWrapper.java
的代码:
当前这个版本仅仅是为了展示 构建者模式 的实现,所以并没有其他逻辑。
public class Client {
public static void main(String[] args) {
HtmlWrapper table = new HtmlWrapper.Builder().setTag("table").setAttrsInTag("border='1' style='border-collapse:collapse'").build();
}
}