java链式编程
链式编程可以使得代码可读性高,链式编程的原理就是返回一个this对象,就是返回本身,达到链式效果,举个例子,下面是一个学生bean
public class StudentBean { private String name; private int age; public String getName() { return name; } public StudentBean setName(String name) { this.name = name; return this; } public int getAge() { return age; } public StudentBean setAge(int age) { this.age = age; return this; } }
这段代码和传统的Bean区别就是我在set属性时候会返回一个this这样就达到了链式编程的效果
public static void main(String[] args) { StudentBean studentBean = new StudentBean().setAge(22).setName("ly"); System.out.println(studentBean.getAge()); System.out.println(studentBean.getName()); }
lombok其实已经提供该style,我们把这个bean改成lombok实现只需要加上一个@Accessors(chain = true)即可
@Accessors(chain = true) @Getter @Setter public class StudentBean { private String name; private int age; }
这样代码简洁多了 ,而且实现了链式编程,那如何用lombok实现一个静态的链式编程呢,再回过头来看刚刚的StudentBean,很多时候,我们去写StudentBean这个bean的时候,他会有一些必输字段,比如StudentBean中的name字段,一般处理的方式是将name字段包装成一个构造方法,只有传入name这样的构造方法,才能创建一个StudentBean对象。
接上上边的静态构造方法和必传参数的构造方法,使用lombok将更改成如下写法(@RequiredArgsConstructor 和 @NonNull):
@Accessors(chain = true) @Getter @Setter @RequiredArgsConstructor(staticName = "of") public class StudentBean { @NonNull private String name; private int age; }
测试方法:
public static void main(String[] args) { StudentBean studentBean = StudentBean.of("ly").setAge(22); System.out.println(studentBean.getAge()); System.out.println(studentBean.getName()); }
这样不仅实现了链式编程,还实现了静态创建,那么怎么实现一个builder模式的链式Bean呢,build模式实现原理为在bean里面创建一个静态builder方法和一个静态内部Builder类,通过调用静态builder方法来创建Builder类,然后通过builder类中的build方法直接创建一个Bean,具体如下:
public class StudentBean { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public static Builder builder() { return new Builder(); } public static class Builder{ private String name; private int age; public Builder name(String name) { this.name = name; return this; } public Builder age(int age) { this.age = age; return this; } public StudentBean build() { StudentBean studentBean = new StudentBean(); studentBean.setName(name); studentBean.setAge(age); return studentBean; } } }
测试方法:
StudentBean studentBean = StudentBean.builder().name("ly").age(11).build();
这样就实现了一个builder模式的链式bean,其实用lombok就一个注解的事情,调用与上面同样
@Builder public class StudentBean { private String name; private int age; }