一.build 介绍
二.实现原理
通过访问静态内部的形式得到内部类,内部类通过有参方法将传入的参数赋值给静态内部类对象,外部类私有构造函数,参数设置成静态内部类对象当静态内部类对象通过无参的build方法获得外部类时,外部类构造函数需要传入静态内部类实例对象,此时,精彩的来了,因为通过访问静态内部的方法获得了内部类对象,而在调用build方法时需要传入内部类对象,而在外部类的私有构造中传入的是静态内部类对象,因此build方法之前全是静态内部类对象,而在build时,确将自己当成参数传入外部类的构造函数中,通过外部类的构造函数里的赋值,得到了外部类对象的实例。
仔细想想,将自己当成参数传入确实精彩
三.应用场景
当需要传入的参数比较多时(超过4个),可以通过此模式
四.代码实现
public class Persion { private String name; private String address; private Integer phoneNum; private Integer age; private Date jobDate; public static class Builder{ private String name = ""; private String address; private Integer phoneNum; private Integer age; private Date jobDate; public Persion build() { return new Persion(this); } public Builder name(String name) { this.name = name; return this; } public Builder address(String address) { this.address = address; return this; } public Builder phoneNum(Integer phoneNum) { this.phoneNum = phoneNum; return this; } public Builder age(Integer age) { this.age = age; return this; } public Builder jobDate(Date jobDate) { this.jobDate = jobDate; return this; } } private Persion(Builder builder) { name = builder.name; age = builder.age; address = builder.address; jobDate = builder.jobDate; } public static void main(String[] args) { Persion persion = new Persion.Builder().name("zhang san").address("北京").age(23).phoneNum(133333) .jobDate(new Date()).build(); System.out.println(persion); } }
原文地址:https://www.cnblogs.com/MrRightZhao/p/10810414.html
时间: 2024-10-10 09:43:52