您好,登錄后才能下訂單哦!
如何使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。