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'}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/260327.html