java Builder模式
2022/9/3 1:23:32
本文主要是介绍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'}
这篇关于java Builder模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南