使用建造者模式创建一个流式API
使用建造者模式创建一个流式API
- 代码如下:
package com.zengpinlin.aopdemo.model; public class User { private String userName; private String age; private String password; /** * 私有构造参数 * * @param build */ private User(Build build) { age = build.age; password = build.password; userName = build.userName; } public static void main(String[] args) { User user = new Build() .age("test") .password("test") .userName("test") .build(); System.out.println("user = " + user); } @Override public String toString() { return "User{" + "userName='" + userName + '\'' + ", age='" + age + '\'' + ", password='" + password + '\'' + '}'; } public static class Build { private String userName; private String age; private String password; public Build() {} public Build(String userName, String age, String password) { this.age = age; this.userName = userName; this.password = password; } public Build userName(String userName) { this.userName = userName; return this; } public Build age(String age) { this.age = age; return this; } public Build password(String password) { this.password = password; return this; } public User build() { return new User(this); } } }
说明:
1.链式的原理也很简单,我的理解就是,内部中每次赋完会返回当前对象,这样就可以进行下次的调用(可以想象成每次我们创一个对象,然后通过对象的引用,进行赋值操作)
2.如果一类有很多属性,可以写成链式调用,这样可以减少客户端的setXX操作,提供代码可读性。