读Android Builder设计模式后实战
来源:互联网 发布:酒店英语口语软件下载 编辑:程序博客网 时间:2024/06/09 20:13
Builder模式
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.
Builder 模式的使用场景
- 相同的方法,不同的执行顺序,产生不同的事件结果时.
- 多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不相同时.
- 产品类非常复杂,或者产品类中的调用顺序不同产生了不同的作用,这个时候使用建造者模式非常合适.
- 当初始化一个对象特别复杂,如参数多,且很多参数都具有默认值时.
例如
package com.softtanck; /** * * @author Tanck * * @date 2015-11-30 14:08:39 * */ public class CarConfig { int wheels;// 轮子数 int color;// 车的颜色 int maxSeat;// 最多座位 int maxSpeed;// 最快速度 // 更多... private CarConfig() { } public static class Builder { private int wheels;// 轮子数 private int color;// 车的颜色 private int maxSeat;// 最多座位 private int maxSpeed;// 最快速度 // 更多... /** * 设置轮子 * * @param wheels * @return */ public Builder setWheels(int wheels) { if (1 >= wheels) wheels = 2;// 默认为2 this.wheels = wheels; return this; } /** * 设置颜色 * * @param color */ public Builder setColor(int color) { this.color = color; return this; } /** * 设置位置 * * @param maxSeat */ public Builder setMaxSeat(int maxSeat) { if (4 <= maxSeat) maxSeat = 4;// 默认为4 this.maxSeat = maxSeat; return this; } /** * 设置速度 * * @param maxSpeed */ public Builder setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; return this; } /** * 应用配置 * * @param carConfig */ private void applyConfig(CarConfig carConfig) { carConfig.color = this.color; carConfig.maxSeat = this.maxSeat; carConfig.maxSpeed = this.maxSpeed; carConfig.wheels = this.wheels; } public CarConfig create() { CarConfig carConfig = new CarConfig(); applyConfig(carConfig); return carConfig; } } }
使用方式
CarConfig carConfig = new CarConfig.Builder() .setColor(1) .setMaxSeat(4) .setWheels(4) .setMaxSpeed(200).create();
优点
- 良好的封装性,使用建造者模式可以使客服端不必知道产品内部组成的细节.
- 建造者独立,容易扩展.
缺点
会产生多余的Builder对象以及Director对象,消耗内存.
0 0
- 读Android Builder设计模式后实战
- Android 设计模式实战 Builder模式
- Java设计模式实战-Builder
- Android设计模式--Builder模式
- android设计模式-Builder模式
- Android设计模式-Builder模式
- android设计模式:Builder模式
- 《Android源码设计模式解析与实战》——Builder模式
- 【读书笔记】Android源码设计模式解析与实战(三)——建造者模式(Builder)
- Android设计模式之Builder
- Android设计模式之Builder
- Android中Builder设计模式
- android设计模式(2)-----builder
- android设计模式之builder
- Android设计模式 Builder设计模式
- android 使用Builder设计模式,设计ToolBar
- Android设计模式——Builder模式
- Android设计模式——Builder模式
- android:inputType参数类型说明
- C语言实现printf的部分功能
- UIButton的常用属性
- ALV的负数符号显示
- 不得不看的Java代码性能优化总结
- 读Android Builder设计模式后实战
- android开发的实用工具类
- hdu1429胜利大逃亡(续)【广搜】
- KNN算法
- 解决EL表达式不能在Js文件中使用
- 扒一扒传智播客深藏在背后的内幕
- android Bluetooth使用相关
- 设计模式第一部分: 单例模式
- Apache Kafka