先说Build的概念,我看到网上有很多关于这个模式的解释说明,我比较认同的是下面的这种理解:
所谓Build模式就是:一步一步将一个复杂对象创建出来,允许用户在不知道内部构建细节的情况下,可以更精细地控制对象的构造流程。
我们最深的体会就是链式编程的运用,这里面基本上都是创建了一个内部静态Build. Android中尤为常见,比如说AlertDialog. 我这里就拿自己做的一个Dialog仿照AlertDialog,运用Build模式来创建,可能封装得有些不完整,但是我一开始的目的就是希望能用到链式编程,所以就算不完整,我还是拿来作为案例讲解。
1.效果图:
2. 没有运用Build模式的写法:
可以看到这个Dialog中,需要传递的参数非常多,总计有8个,按照普通写法,可能在new Dialog中需要一次性传递8个参数,不要笑话我,我开始赶进度的时候确实是这么做的。
public EffectDialog(Context context, int themeResId,String effect,String visit,String praise,
String comment,String share,String collection,String reward,String speed) {
super(context, themeResId);
mEffect = effect;
mVisit = visit;
mPraise = praise;
mComment = comment;
mShare = share;
mCollection = collection;
mReward = reward;
mSpeed = speed;
}
然后在调用的地方,使劲的传参数,还时不时看有没有传错位。太痛苦了。
然后痛定思痛,开始改造。
3. 改造成Build模式
先看源码AlertDialog, 有个AlertController
private AlertController mAlert;
还有个内部静态类Builder,我这里只摘抄几个方法:
public static class Builder {
private final AlertController.AlertParams P;
public Builder(Context context) {
this(context, resolveDialogTheme(context, 0));
}
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}
..........
还有个就是要看AlertDialog的OnCreate方法:
@Override