1.概念
建造者模式是一种创建型设计模式,它允许我们一步一步的来构造对象,其实就是将创建对象的一个过程拆分成了很多个小步骤,常见主要是在一个A类的基础上,加多一个Builder的类,然后属性和A类的一样,我们在创建A类的对象时不直接通过new A()的形式,而是通过new Builder()创建一个Builder对象,然后调用各个方法去设置Builder对象属性最后再去new A()对象,并且各个属性的值均从Builder对象里取。
2.Cat类
package com.yl.pattern.builder;public class Cat {private long id;private String name;private int age;private String gender;public Cat(long id,String name,int age,String gender) {this.id = id;this.name = name;this.age = age;this.gender = gender;}@Overridepublic String toString() {return "id=" + id + ",name=" + name +",age=" + age + ",gender=" + gender;}
}
3.Cat Builder
package com.yl.pattern.builder;public class CatBuilder {private long id;private String name;private int age;private String gender;public CatBuilder setId(long id) {this.id = id;return this;}public CatBuilder setName(String name) {this.name = name;return this;}public CatBuilder setAge(int age) {this.age = age;return this;}public CatBuilder setGender(String gender) {this.gender = gender;return this;}public Cat build() {return new Cat(id,name,age,gender);}}
4.demo
package com.yl.pattern.builder;public class Demo {public static void main(String[] args) {CatBuilder catBuilder = new CatBuilder();Cat cat = catBuilder.setId(1).setName("小鱼").setAge(18).setGender("male").build();System.out.println(cat);}
}