建造者模式
来源:互联网 发布:淘宝搜店铺名搜不到 编辑:程序博客网 时间:2024/06/07 23:31
定义
- 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
优点
- 建造者独立,易扩展
- 便于控制细节风险
缺点
- 产品必须有共同点,范围有限制
- 内部变化复杂,会有很多的建造类
注意点
- 与工厂模式相比较,建造模式更加关注与零件装配的顺序
第一步
- 创建 Person 类
public class Person { private String name; private int age; private double height; private double weight; public Person(PersonalBinder personalBinder) { this.name = personalBinder.name; this.age = personalBinder.age; this.height = personalBinder.height; this.weight = personalBinder.weight; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; }}
第二步
- 创建 PersonalBinder 类
public class PersonalBinder { public String name; public int age; public double height; public double weight; public PersonalBinder name(String name) { this.name = name; return this; } public PersonalBinder age(int age) { this.age = age; return this; } public PersonalBinder height(Double height) { this.height = height; return this; } public PersonalBinder weight(Double weight) { this.weight = weight; return this; } public Person bind() { return new Person(this); }}
#### 第三步
- 创建 Demo 测试
public class PersonDemo { public static void main(String[] args) { PersonalBinder personalBinder = new PersonalBinder(); Person person = personalBinder .name("张三") .age(12) .height(175d) .weight(70d) .bind(); System.out.println("name:" + person.getName() + ",age:" + person.getAge() + ",height:" + person.getHeight() + ",weight:" + person.getWeight()); }}
第四步
- 收获结果
name:张三,age:12,height:175.0,weight:70.0
阅读全文
0 0
- Builder 建造者模式
- 建造者模式
- 设计模式-------建造者
- 建造者模式
- 建造者模式(Builder)
- 建造者模式(Builder)
- 建造者模式
- 建造者模式 - builder
- 建造者模式
- Builder建造者模式
- 建造者模式(Builder)
- 建造者模式(builder)
- 建造者模式
- java建造者模式
- 建造者模式
- 建造者模式
- 建造者模式(Builder)
- 建造者模式
- How to revert the code/files that have been merged to the remote Repo
- 继承(单继承、多继承、菱形继承、虚继承)
- JS检测移动端横竖屏
- Android studio中添加系统jar包提高优先级
- django使用celery做异步执行过程
- 建造者模式
- POJ A Round Peg in a Ground Hole <凸包判断以及点与多边形的相对位置>
- 正确使用 Volatile 变量
- 配置本地Gradle
- python3调用百度翻译接口样例
- 微信小程序 图片宽高自适应详解
- BaseRecyclerViewAdapterHelper简单使用
- 【Unity3D技术文档翻译】第1.6篇 使用 AssetBundle Manager
- java.lang.OutOfMemoryError: PermGen space