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模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程