介绍
该模式为了将构建复杂对象的过程和他的部件解耦,使得构建构成和部件的表示隔离开。
UML
UML.png上代码
package com.ralap.builder;
/**
* Created by ralap on 2017/9/27.
*/
public class Computers {
private final String mCpu;
private final String mDisplay;
private final String mOs;
private Computers(Builder builder) {
this.mCpu = builder.cpu;
this.mDisplay = builder.display;
this.mOs = builder.os;
}
public static class Builder {
private final String cpu;
private String display;
private String os;
public Builder(String cpu) {
this.cpu = cpu;
}
public Builder display(String display) {
this.display = display;
return this;
}
public Builder os(String os) {
this.os = os;
return this;
}
public Computers create() {
return new Computers(this);
}
}
public String getmCpu() {
return mCpu;
}
public String getmDisplay() {
return mDisplay;
}
public String getmOs() {
return mOs;
}
}
说明
- Computers构造私有;
- 不可变参数使用final,防止后续修改;
- Bullder的设置参数使用链式
优缺点:
- 优点:
- 良好的封装性,使用构建者模式可以是客户端不必知道看平内部的组成细节;
- 构建者独立,容易扩展;
- 缺点
- 会产生多余的Builder对象,消耗内存;
网友评论