建造模式
1、当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
2、当构造过程必须允许被构造的对象有不同表示时。
根门面模式有些类似
//构建一个用户对象
public class User {
private String name;//名称
private String sex;//性别
private Integer age;//年龄
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
//构建方法
public interface GetUser {
void getName();
void getSex();
void getAge();
User user();
}
//实现构建方法的内容
public class SetUser implements GetUser{
User user;
public SetUser() {
}
public SetUser(User user) {
this.user = user;
}
@Override
public void getName() {
user.setName("取名字");
}
@Override
public void getSex() {
user.setSex("男");
}
@Override
public void getAge() {
user.setAge(10);
}
@Override
public User user() {
return user;
}
}
public class SetUser2 implements GetUser{
User user;
public SetUser2() {
}
public SetUser2(User user) {
this.user = user;
}
@Override
public void getName() {
user.setName("取名字2");
}
@Override
public void getSex() {
user.setSex("女");
}
@Override
public void getAge() {
user.setAge(11);
}
@Override
public User user() {
return user;
}
}
//通过对象构建用户信息
public class Build {
public User sev(GetUser getUser){
getUser.getAge();
getUser.getName();
getUser.getSex();
return getUser.user();
}
}
//测试
public class Test {
public static void main(String[] args) {
Build build = new Build();
User user = build.sev(new SetUser());
User user2 = build.sev(new SetUser2());
}
}