建造者模式

来源:互联网 发布:淘宝搜店铺名搜不到 编辑:程序博客网 时间: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:12height:175.0weight:70.0
原创粉丝点击