利用Builder方式创建对象示例代码
前言
在创建对象需要初始化数据,数据参数不容易区别,可传可不传的时候,可以考虑使用Builder建造方法创建。每每当看到别人写的用Bulder方式来调用,就觉得so cool,那就自己也来用Builder方式创建对象吧。
下面话不多说了,来一起看看详细的介绍吧
现在要录入一系列人员的基本信息的示例:
创建Person类
public class Person { private String name; private int age; private float height; private float weight; public Person(String name, int age, float height, float weight) { this.name = name; this.age = age; this.height = height; this.weight = 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 float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } }
那么创建对象就是这样,后面参数不容易看出表示的是什么,可读性不强
new Person("冯提莫",18,150,43); new Person("温婉",17,164,48);
用Builder模式进行改造
创建一个Builder类,属性和Person类一样,加上SetXxx()方法
static class Builder{ private String name; private int age; private float height; private float weight; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setHeight(float height) { this.height = height; } public void setWeight(float weight) { this.weight = weight; } }
将Person的构造方法改为传入Builder对象,将Builder对象的属性值都赋予Person对象
public Person(Builder builder){ this.name = builder.name; this.age = builder.age; this.height = builder.height; this.weight = builder.weight; }
改造Builder类,关键步骤是将各个set方法返回Builder类对象,这样就能继续愉快地连续调用set方法了,最后调用build()创建方法返回Person对象。
static class Builder{ private String name; private int age; private float height; private float weight; public Builder setName(String name) { this.name = name; return this; } public Builder setAge(int age) { this.age = age; return this; } public Builder setHeight(float height) { this.height = height; return this; } public Builder setWeight(float weight) { this.weight = weight; return this; } public Person build(){ return new Person(this); } }
将各个set方法的返回值类型改为Builder,每次都返回builder对象,这样才能将set方法实现连续的链式调用。
build()方法创建一个person对象,会调用Person的带参构造方法,将builder对象的属性依次赋予person对象。person中的属性值就是链式调用set方法的各个值。
使用Builder模式创建Person对象,明显看出代码可读性大大增强。注:Builder创建方式通常是在创建的对象少的情况下使用。
Person person = new Person.Builder() .setName("莉哥") .setAge(20) .setHeight(162) .setWeight(45) .build();
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我们的支持。
赞 (0)