Builder模式常用于配置对象属性。如果需要在构建对象时设置各参数,之后属性不再修改(没有setter方法)时,可以采用此模式。
Universal-Image-Loader图片加载库
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
config.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.diskCacheFileNameGenerator(new Md5FileNameGenerator())
.diskCacheSize(50 * 1024 * 1024)
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config.build());
Builder模式实战:
public final class ImageLoader {
private ImageLoaderConfig mConfig;
/** 初始化ImageLoader
* @param config
*/
public void init(ImageLoaderConfig config) {
}
}
public class ImageLoaderConfig {
//图片缓存配置对象
BitmapCache bitmapCache = new MemoryCache();
//加载图片时的loading的图片配置对象
DisplayConfig displayConfig = new DisplayConfig();
//线程数量
int threadCount = Runtime.getRuntime().availableProcessors() + 1;
private ImageLoaderConfig(){
mConfig = config;
... ...
}
/**
* 配置类的Builder
*/
public static class Builder {
//图片缓存配置对象
BitmapCache bitmapCache = new MemoryCache();
//加载图片时的loading的图片配置对象
DisplayConfig displayConfig = new DisplayConfig();
//线程数量
int threadCount = Runtime.getRuntime().availableProcessors() + 1;
//设置线程数量
public Builder setThreadCount(int count) {
threadCount = Math.max(1, count);
return this;
}
//设置缓存
public Builder setCache(BitmapCache cache) {
bitmapCache = cache;
return this;
}
//设置图片加载中显示的图片
public Builder setLoadingPlaceholder(int resId){
displayConfig.loadingResId = resId;
return this;
}
void applyConfig(ImageLoaderConfig config) {
config.bitmapCache = this.bitmapCache;
config.displayConfig = this.displayConfig;
config.threadCount = this.threadCount;
}
/**
* 根据已经设置好的属性创建配置对象
* @return ImageLoaderConfig对象
*/
public ImageLoaderConfig create() {
ImageLoaderConfig config = new ImageLoaderConfig();
//应用配置
applyConfig(config);
return config;
}
}
}
通过将ImageLoaderConfig的构造函数、字段私有化,使得外部不能访问内部属性。用户只能提供Builder对象构造ImageLoaderConfig对象,这就是构建和表示相分离。
private void initImageLoader(){
ImageLoaderConfig config = new ImageLoaderConfig.Builder()
.setLoadingPlaceholder(R.drawable.loading)
.setCache(new DoubleCache(this))
.setThreadCount(4)
.create();
//将配置初始化到ImageLoader中
ImageLoader.getInstance().init(config);
}
调用init函数后,ImageLoader就可以正常使用了,各种setter函数不会在用户调用ImageLoader方法时出现在视野中,它们已经被隔离到了Builder模式中。