-
生成器模式
(1) 又称建造者模式,将构建过程和表示过程进行分离,让(参数)构建过程变得更加的简单和直观。另一种差不多的解释:建造者模式(Builder Pattern),是创造性模式之一,Builder 模式的目的则是为了将对象的构建与展示分离。Builder 模式是一步一步创建一个复杂对象的创建型模式,它允许用户在不知道内部构建细节的情况下,可以更精细地控制对象的构造流程。
(2) 示例
public class Person { private String name; private String sex; private double height; private double weight; private String country; private String homeTown; private Person(String name, String sex, double height, double weight, String country, String homeTown) { this.name = name; this.sex = sex; this.height = height; this.weight = weight; this.country = country; this.homeTown = homeTown; } static final class Builder { private String name; private String sex; private double height; private double weight; private String country; private String homeTown; public Builder setName(String name) { this.name = name; return this; } public Builder setSex(String sex) { this.sex = sex; return this; } public Builder setHeight(double height) { this.height = height; return this; } public Builder setWeight(double weight) { this.weight = weight; return this; } public Builder setCountry(String country) { this.country = country; return this; } public Builder setHomeTown(String homeTown) { this.homeTown = homeTown; return this; } public Person build() { return new Person(name, sex, height, weight, country, homeTown); } } }
测试
public class TestPerson { public static void main(String[] args) { Person.Builder builder = new Person.Builder(); Person me = builder.setName("BoCHEN") .setCountry("China") .setHeight(1.78) .setHomeTown("LN") .setSex("Male") .setWeight(61.2).build(); System.out.println(); }
(3) 优点
1° 可读性强
链式调用, 一行搞定, 不用好几行各种set了
2° 可选择性强
如果采取构造函数的形式的话, 当内部域很多时, 需要创建一大堆构造函数; 使用builder模式可以只set那些需要set的参数, 其他可以使用默认值
-
未完待续……
网友评论