小编给大家分享一下java怎么创建一个女朋友类(对象啥的new一个就是)==建造者模式,一键重写,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
相比如文字解释,我更习惯撸代码来解释,下面来一步步实现怎么用java来为你创建一个女朋友
首先定义一个女朋友类:
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;//类型
按照我们以往的理解,要创建一个女朋友是不是要直接new出来,我们可以通过构造方法把属性传过去
例如:我对女朋友的要求只有一个,是女的就行,定义一个构造方法:
public GirlFriend(String sex) {
this.sex = sex;
}
然后再需要的时候来创建她:
GirlFriend girlFriend = new GirlFriend("女");
如果我们要求性别和身高就要定义:
public GirlFriend(String sex, int stature) {
this.sex = sex;
this.stature = stature;
}
你想想每个人的要求都不一样,你得创建多少个构造方法,而且参数多了,可读性很差比如:
GirlFriend girlFriend = new GirlFriend("女",19,170,90,"声优");
java有一个建造者模式:
建造一个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;
}
/**
*返回一个GirlFriend对象
*/
public GirlFriend build() {
return new GirlFriend(this);
}
}
然后在GirlFriend类里面构造方法传入GirlFriendBuilder对象:
public GirlFriend(GirlFriendBuilder builder) {
this.sex = builder.sex;
this.age = builder.age;
this.stature = builder.stature;
this.weight = builder.weight;
this.type = builder.type;
}
然后创建的时候:
GirlFriend girlFrie1nd = new GirlFriendBuilder()
.setAge(19)
.setSex("女")
.setType("声优")
.setStature(175)
.build();
这样就成功创建了一个女朋友,代码的可读性也挺高的
看完了这篇文章,相信你对“java怎么创建一个女朋友类(对象啥的new一个就是)==建造者模式,一键重写”有了一定的了解,如果想了解更多相关知识,欢迎关注天达云行业资讯频道,感谢各位的阅读!