前言
Builder建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。可以在用户不知道对象的建造过程和细节的情况下就可以直接创建复杂的对象。
1. 建造者模式
我们以建造一个房子为例,配置诸如地板、墙、窗、布局等,我们采用建造者模式去完成。
IBuilder接口:
public interface IBuilder {
IBuilder makeWindow(String window);
IBuilder makeFloor(String floor);
IBuilder paintWall(String brand);
IBuilder designLayout(String layout);
Room build();
}
WorkBuilder建造者类:
public class WorkBuilder implements IBuilder {
private RoomParams roomParams;
private final Room room;
public WorkBuilder () {
room = new Room();
roomParams = new RoomParams();
}
@Override
public IBuilder makeWindow(String window) {
roomParams.window = window;
return this;
}
@Override
public IBuilder makeFloor(String floor) {
roomParams.floor = floor;
return this;
}
@Override
public IBuilder paintWall(String brand) {
roomParams.brand = brand;
return this;
}
@Override
public IBuilder designLayout(String layout) {
roomParams.layout = layout;
return this;
}
@Override
public Room build() {
room.apply(roomParams);
return room;
}
public class RoomParams {
public String window;
public String floor;
public String brand;
public String layout;
}
}
Room房子类:
public class Room {
private String window;
private String floor;
private String brand;
private String layout;
public Room apply(WorkBuilder.RoomParams roomParams) {
window = roomParams.window;
floor = roomParams.floor;
brand = roomParams.brand;
layout = roomParams.layout;
return this;
}
@Override
public String toString() {
return "Room{" +
"window='" + window + '\'' +
", floor='" + floor + '\'' +
", brand='" + brand + '\'' +
", layout='" + layout + '\'' +
'}';
}
}
Client客户:
public class Client {
public static void main(String[] args) {
WorkBuilder workBuilder = new WorkBuilder();
Room room = workBuilder.makeFloor("防滑地板")
.makeWindow("落地窗")
.paintWall("立邦粉刷")
.designLayout("三室一厅")
.build();
System.out.println("建造的房子:" + room);
}
}
输出结果:
建造的房子:Room{window='落地窗', floor='防滑地板', brand='立邦粉刷', layout='三室一厅'}
其实建造者模式采用的就是链式调用的方式,将构建与表示相分离。
2. 建造者模式在Android中的应用
AlertDialog的源码(具体源码解析可以查看AlertDialog源码解析)、Glide图片加载库源码、OKHttp网络访问库源码、RxJava链式调用库源码等。
3. 总结
建造者模式在Android中应用比较广泛,大部分复杂的一些源码都设计到了建造者模式。建造者模式优点在于易于解耦、易于精确控制对象的创建、易于拓展,但是缺点在于如果产品的内部变化复杂,可能需要定义很多具体的构造者,导致系统庞大。
喜欢本篇博客的简友们,就请来一波点赞,您的每一次关注,将成为我前进的动力,谢谢!