您好,登錄后才能下訂單哦!
小編給大家分享一下java怎么創(chuàng)建一個(gè)女朋友類(對(duì)象啥的new一個(gè)就是)==建造者模式,一鍵重寫,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
相比如文字解釋,我更習(xí)慣擼代碼來解釋,下面來一步步實(shí)現(xiàn)怎么用java來為你創(chuàng)建一個(gè)女朋友
首先定義一個(gè)女朋友類:
package nuoyanli; /** * Created by ${nuoyanli} on 2019/4/7. */ public class GirlFriend { private String sex;//性別 private int age;//年齡 private int stature;//身高 private int weight;//體重 private String type;//類型
按照我們以往的理解,要?jiǎng)?chuàng)建一個(gè)女朋友是不是要直接new出來,我們可以通過構(gòu)造方法把屬性傳過去
例如:我對(duì)女朋友的要求只有一個(gè),是女的就行,定義一個(gè)構(gòu)造方法:
public GirlFriend(String sex) { this.sex = sex; }
然后再需要的時(shí)候來創(chuàng)建她:
GirlFriend girlFriend = new GirlFriend("女");
如果我們要求性別和身高就要定義:
public GirlFriend(String sex, int stature) { this.sex = sex; this.stature = stature; }
你想想每個(gè)人的要求都不一樣,你得創(chuàng)建多少個(gè)構(gòu)造方法,而且參數(shù)多了,可讀性很差比如:
GirlFriend girlFriend = new GirlFriend("女",19,170,90,"聲優(yōu)");
java有一個(gè)建造者模式:
建造一個(gè)GirlFriendBuilder類:
package nuoyanli; /** * Created by ${nuoyanli} on 2019/4/7. */ public class GirlFriendBuilder { String sex;//性別 int age;//年齡 int stature;//身高 int weight;//體重 String type;//類型 public GirlFriendBuilder setSex(String sex) { this.sex = sex; return this; } public GirlFriendBuilder setAge(int age) { this.age = age; return this; } public GirlFriendBuilder setStature(int stature) { this.stature = stature; return this; } public GirlFriendBuilder setWeight(int weight) { this.weight = weight; return this; } public GirlFriendBuilder setType(String type) { this.type = type; return this; } /** *返回一個(gè)GirlFriend對(duì)象 */ public GirlFriend build() { return new GirlFriend(this); } }
然后在GirlFriend類里面構(gòu)造方法傳入GirlFriendBuilder對(duì)象:
public GirlFriend(GirlFriendBuilder builder) { this.sex = builder.sex; this.age = builder.age; this.stature = builder.stature; this.weight = builder.weight; this.type = builder.type; }
然后創(chuàng)建的時(shí)候:
GirlFriend girlFrie1nd = new GirlFriendBuilder() .setAge(19) .setSex("女") .setType("聲優(yōu)") .setStature(175) .build();
這樣就成功創(chuàng)建了一個(gè)女朋友,代碼的可讀性也挺高的
看完了這篇文章,相信你對(duì)“java怎么創(chuàng)建一個(gè)女朋友類(對(duì)象啥的new一個(gè)就是)==建造者模式,一鍵重寫”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(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)容。