建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
一个 Builder 类会一步一步构造最终的对象。该 Builder 类是独立于其他对象的。
意图
将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。
实现
我们这边实现一个功能如下
要制作一套衣服,上衣有多件,裤子有多件,可以组成的衣服就有很多种了
建造者模式就是创建一个Builder,按照不同的需求创建不同的多套衣服。
- 创建产品
public class Clothes{
private String Coat;
private String Pants;
public String getCoat() {
return Coat;
}
public void setCoat(String coat) {
Coat = coat;
}
public String getPants() {
return Pants;
}
public void setPants(String pants) {
Pants = pants;
}
@Override
public String toString() {
return "Clothes{" +
"Coat='" + Coat + '\'' +
", Pants='" + Pants + '\'' +
'}';
}
}
- 创建Builder抽象类
public abstract class Builder{
public abstract void setClothes(String Coat,String Pants);
public abstract Clothes getClothes();
}
- 创建Builder实体类
public class ClothesBuilder extends Builder{
private Clothes mClothes = new Clothes();
@Override
public void setClothes(String Coat, String Pants) {
mClothes.setCoat(Coat);
mClothes.setPants(Pants);
}
@Override
public Clothes getClothes() {
return mClothes;
}
}
- 创建导演类
public class ClothesSuit{
private Builder builder = new ClothesBuilder();
public Clothes getClothes1(){
builder.setClothes("衬衫","西裤");
return builder.getClothes();
}
public Clothes getClothes2(){
builder.setClothes("短袖","短裤");
return builder.getClothes();
}
}
- 使用
public static void main(String... args) {
ClothesSuit clothesSuit = new ClothesSuit();
Clothes clothes = clothesSuit.getClothes1();
System.out.println(clothes.toString());
clothes = clothesSuit.getClothes2();
System.out.println(clothes.toString());
}
- 结果
I/System.out: Clothes{Coat='衬衫', Pants='西裤'}
I/System.out: Clothes{Coat='短袖', Pants='短裤'}