您好,登錄后才能下訂單哦!
如何使用Builder方式創(chuàng)建一個(gè)對(duì)象?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
創(chuàng)建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; } }
那么創(chuàng)建對(duì)象就是這樣,后面參數(shù)不容易看出表示的是什么,可讀性不強(qiáng)
new Person("馮提莫",18,150,43); new Person("溫婉",17,164,48);
用Builder模式進(jìn)行改造
創(chuàng)建一個(gè)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的構(gòu)造方法改為傳入Builder對(duì)象,將Builder對(duì)象的屬性值都賦予Person對(duì)象
public Person(Builder builder){ this.name = builder.name; this.age = builder.age; this.height = builder.height; this.weight = builder.weight; }
改造Builder類,關(guān)鍵步驟是將各個(gè)set方法返回Builder類對(duì)象,這樣就能繼續(xù)愉快地連續(xù)調(diào)用set方法了,最后調(diào)用build()創(chuàng)建方法返回Person對(duì)象。
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); } }
將各個(gè)set方法的返回值類型改為Builder,每次都返回builder對(duì)象,這樣才能將set方法實(shí)現(xiàn)連續(xù)的鏈?zhǔn)秸{(diào)用。
build()方法創(chuàng)建一個(gè)person對(duì)象,會(huì)調(diào)用Person的帶參構(gòu)造方法,將builder對(duì)象的屬性依次賦予person對(duì)象。person中的屬性值就是鏈?zhǔn)秸{(diào)用set方法的各個(gè)值。
使用Builder模式創(chuàng)建Person對(duì)象,明顯看出代碼可讀性大大增強(qiáng)。注:Builder創(chuàng)建方式通常是在創(chuàng)建的對(duì)象少的情況下使用。
Person person = new Person.Builder() .setName("莉哥") .setAge(20) .setHeight(162) .setWeight(45) .build();
關(guān)于如何使用Builder方式創(chuàng)建一個(gè)對(duì)象問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。