利用Builder方式创建对象示例代码
程序员文章站
2023-11-09 09:01:58
前言
在创建对象需要初始化数据,数据参数不容易区别,可传可不传的时候,可以考虑使用builder建造方法创建。每每当看到别人写的用bulder方式来调用,就觉得so co...
前言
在创建对象需要初始化数据,数据参数不容易区别,可传可不传的时候,可以考虑使用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();
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。