分步构建模式
public class StepBuilder {
/**
* Step Builder Pattern【分步构建模式】:
* 明确指定具体的构建步骤执行什么操作
*/
@Test
public void all() {
final Long id = Long.valueOf(1);
final User user = User.stepBuilder()
.id(id)
.name("zxd")
.hoppy("sleep")
.hoppy("eat")
.hoppy("work")
.build();
assertEquals(id,user.getId());
}
}
@Getter
class User{
private final Long id;
private final String name;
private final List<String> hoppies;
@SuppressWarnings("synthetic-access")
public static IdBuiler stepBuilder() {
return new UserStepBuilder();
}
private User(Long id, String name, List<String> hoppies) {
this.id = id;
this.name = name;
this.hoppies = hoppies;
}
public interface IdBuiler {
NameBuilder id(Long id);
}
public interface NameBuilder{
HoppyBuilder name(String name);
}
public interface HoppyBuilder{
HoppyBuilder hoppy(String hoppy);
User build();
}
private static class UserStepBuilder implements IdBuiler,NameBuilder,HoppyBuilder{
private Long id;
private String name;
private List<String> hoppies;
@Override
public User build() {
return new User(id, name, hoppies);
}
@Override
public HoppyBuilder hoppy(String hoppy) {
hoppies.add(hoppy);
return this;
}
@Override
public HoppyBuilder name(String name) {
this.name=name;
hoppies=Lists.newArrayList();
return this;
}
@Override
public NameBuilder id(Long id) {
this.id=id;
return this;
}
}
}