介绍
建造者模式使用多个简单对象一步步创建复杂对象。
主要解决:将构建复杂对象的过程和它的部件解耦,使得构建过程和部件的表示隔离开来。
使用场景:
1.需要生成的对象具有复杂的内部结构
2.类中的调用顺序不同产生不同的作用
3.多个部件或零件,都可以装配到一个对象中,但是产生的运行结果不相同。
优点:
- 良好的封装性,使用建造者模式可以使客户端不必知道产品内部的细节。
- 建造者独立,容易扩展。
缺点:
- 会有很多Builder类
UML类图
代码实现
Phone.java
public abstract class Phone {
protected String color;
protected String os;
public void setColor(String color) {
this.color = color;
}
public abstract void setOS();
}
ApplePhone.java
public class ApplePhone extends Phone{
@Override
public void setOS() {
this.os = "iOS";
}
}
Vivo.java
public class Vivo extends Phone{
@Override
public void setOS() {
this.os = "Android";
}
}
Builder.java
public abstract class Builder {
public abstract void setColor(String color);
public abstract void setOS();
public abstract Phone create();
}
ApplePhoneBuilder.java
public class ApplePhoneBuilder extends Builder{
private Phone iPhone = new ApplePhone();
@Override
public void setColor(String color) {
iPhone.setColor(color);
}
@Override
public void setOS() {
iPhone.setOS();
}
@Override
public Phone create() {
return iPhone;
}
}
VivoBuilder.java
public class VivoBuilder extends Builder{
private Phone vivo = new Vivo();
@Override
public void setColor(String color) {
vivo.setColor(color);
}
@Override
public void setOS() {
vivo.setOS();
}
@Override
public Phone create() {
return vivo;
}
}
Director.java
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void construct(String color) {
builder.setColor(color);
builder.setOS();
}
}
Main.java
public class Main {
public static void main(String[] args) {
Builder iPhoneBuilder = new ApplePhoneBuilder();
Director director = new Director(iPhoneBuilder);
director.construct("Blue");
}
}
网友评论