java Builder模式
作者:互联网
Builder 模式也叫建造者模式,builder模式的作用将一个复杂对象的构建与他的表示分离,一步一步创建一个复杂对象的创建型模式。在不知道内部建造细节的情况下,可以更精细的控制对象的构造流程。目的就是为了解耦。
public class UserInfo { private String name; private String zhName; private String account; private String password; public UserInfo(String name, String zhName, String account, String password) { this.name = name; this.zhName = zhName; this.account = account; this.password = password; } public UserInfo() { } public static class Builder{ private String name; private String zhName; private String account; private String password; public Builder name(String name){ this.name = name; return this; } public Builder zhName(String zhName){ this.zhName = zhName; return this; } public Builder account(String account){ this.account = account; return this; } public Builder password(String password){ this.password = password; return this; } public UserInfo build(){ return new UserInfo(this.name,this.zhName,this.account,this.password); } } public static Builder builder() { return new Builder(); } @Override public String toString() { return "UserInfo{" + "name='" + name + '\'' + ", zhName='" + zhName + '\'' + ", account='" + account + '\'' + ", password='" + password + '\'' + '}'; } }
public static void main(String[] args) { UserInfo userInfo=UserInfo.builder() .name("小明") .zhName("夏明") .account("xxx@qw.com") .password("asdqwer") .build(); System.out.println(userInfo); }
UserInfo{name='小明', zhName='夏明', account='xxx@qw.com', password='asdqwer'}
标签:account,java,String,Builder,模式,zhName,password,public,name 来源: https://www.cnblogs.com/eternality/p/16649775.html