(一)建造者模式
2018-01-04 本文已影响7人
清晨的麦田
构建类TVBuild:
package Builder;
public class TVBuild {
private static TV tv;
private static TVBuild tvBuild = new TVBuild();
private TVBuild() {
}
public static TVBuild getInstance() {
return tvBuild;
}
public TVBuild buildTV() {
tv = new TV();
return this;
}
public TVBuild setColor(String Color) {
tv.setTvColor(Color);
return this;
}
public TVBuild OpenTV(boolean bool) {
tv.setOpen(bool);
return this;
}
public TVBuild build() {
System.out.println(tv.toString());
return this;
}
}
产品类:
class TV {
@Override
public String toString() {
return "TVBuild{" +
"tvColor='" + tvColor + '\'' +
", isOpen=" + isOpen +
'}';
}
private String tvColor;
private boolean isOpen;
public String getTvColor() {
return tvColor;
}
public void setTvColor(String tvColor) {
this.tvColor = tvColor;
}
public boolean isOpen() {
return isOpen;
}
public void setOpen(boolean open) {
isOpen = open;
}
}
运行:
import Builder.TVBuild;
public class Main {
public static void main(String[] args) {
TVBuild.getInstance().buildTV()
.OpenTV(true)
.setColor("red").build();
}
}
输出:
TVBuild{tvColor='red', isOpen=true}