Java教程

Java-Builder模式

本文主要是介绍Java-Builder模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/**
 * 当一个对象有多个可选构造参数,可以选择builder模式构造对象,
 * 通过有意义的函数名称来避免构造对象的时参数犯迷糊
 * @author orange
 * @description
 */
public class Person {
    private String name;
    private int age;
    private String address;
    private String telNum;
    private boolean isMarriage;
    private String company;


    public static class Builder{
        //required
        private final String name;
        private final  int age;
        //optional
        private String address="";
        private String telNum="";
        private boolean isMarriage=false;
        private String company="";
        public Builder (String name,int age){
            this.name=name;
            this.age=age;
        }
        public Builder address(String val){
            address=val;
            return this;
        }
        public Builder telNum(String val){
            telNum=val;
            return this;
        }
        public Builder isMarriage(boolean val){
            isMarriage=val;
            return this;
        }
        public Builder company(String val){
            company=val;
            return this;
        }
        public Person build(){
            return new Person(this);
        }
    }

    private Person(Builder builder){
        this.name=builder.name;
        this.age=builder.age;
        this.address=builder.address;
        this.telNum=builder.telNum;
        this.isMarriage=builder.isMarriage;
        this.company=builder.company;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", telNum='" + telNum + '\'' +
                ", isMarriage=" + isMarriage +
                ", company='" + company + '\'' +
                '}';
    }
}
这篇关于Java-Builder模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!