如何使用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();
关于如何使用Builder方式创建一个对象问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。