• Java 链式编程 和 lombok 实现链式编程


    一、链式编程定义

    链式编程的原理就是返回一个this对象,就是返回本身,达到链式效果。

    二、jdk中 StringBuffer 源码

    我们经常用的 StringBuffer 就是 实现了链式的写法。

    StringBuffer builder = new StringBuffer();
    builder.append("blake").append("bob").append("alice").append("linese").append("eve");
    

    是不是很方便呢!

    怎么实现呢,其实就是在设置的 返回当前的对象 。

    源码如下:

    @Override
    public StringBuilder append(String str) {
        super.append(str);
        return this;
    }
    

    三、按照上面的方法写一个例子

    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;
    	}
    }
    

    测试:

    public class Main {
    
    	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 链式编程

    其实,lombok 已经提供该 style,我们把这个bean 改成 lombok 实现只需要加上一个 @Accessors(chain = true) 即可。

    @Accessors(chain = true)
    @Getter
    @Setter
    public class StudentBean {
    
    	private String name;	
    	private int age;
    	
    }
    

    上面代码编译之后:

    public class StudentBean {
        private String name;
        private int age;
    
        public StudentBean() {
        }
    
        public String getName() {
            return this.name;
        }
    
        public int getAge() {
            return this.age;
        }
    
        public StudentBean setName(String name) {
            this.name = name;
            return this;
        }
    
        public StudentBean setAge(int age) {
            this.age = age;
            return this;
        }
    }
    

    五、lombok 实现静态的链式编程

    写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 class StudentBean {
        @NonNull
        private String name;
        private int age;
    
        @NonNull
        public String getName() {
            return this.name;
        }
    
        public int getAge() {
            return this.age;
        }
    
        public StudentBean setName(@NonNull String name) {
            if (name == null) {
                throw new NullPointerException("name");
            } else {
                this.name = name;
                return this;
            }
        }
    
        public StudentBean setAge(int age) {
            this.age = age;
            return this;
        }
    
        private StudentBean(@NonNull String name) {
            if (name == null) {
                throw new NullPointerException("name");
            } else {
                this.name = name;
            }
        }
    
        public static StudentBean of(@NonNull String name) {
            return new StudentBean(name);
        }
    }
    

    测试方法:

    public class Main {	
    	public static void main(String[] args) {		
    		StudentBean studentBean = StudentBean.of("zhangsan").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("zhangsan").age(11).build();
    

    七、lombok 实现 builder模式的链式bean

    这样就实现了一个builder模式的链式bean。其实用lombok就一个注解的事情,调用与上面同样

    @Builder
    public class StudentBean {
    	private String name;
    	
    	private int age;
    }
    

    上面代码编译之后:

    public class StudentBean {
        private String name;
        private int age;
    
        StudentBean(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public static StudentBean.StudentBeanBuilder builder() {
            return new StudentBean.StudentBeanBuilder();
        }
    
        public static class StudentBeanBuilder {
            private String name;
            private int age;
    
            StudentBeanBuilder() {
            }
    
            public StudentBean.StudentBeanBuilder name(String name) {
                this.name = name;
                return this;
            }
    
            public StudentBean.StudentBeanBuilder age(int age) {
                this.age = age;
                return this;
            }
    
            public StudentBean build() {
                return new StudentBean(this.name, this.age);
            }
    
            public String toString() {
                return "StudentBean.StudentBeanBuilder(name=" + this.name + ", age=" + this.age + ")";
            }
        }
    }
    

    可以发现添加了 @Builder 注解之后,自动生成了静态builder方法 和一个 静态内部Builder类,并没有生成 get、set 方法,我们在上面例子中加入 @Data@Accessors(chain = true)注解:

    @Builder
    @Data
    @Accessors(chain = true)
    public class StudentBean {
        private String name;
    
        private int age;
    }
    

    上面代码编译之后:

    public class StudentBean {
        private String name;
        private int age;
    
        StudentBean(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public static StudentBean.StudentBeanBuilder builder() {
            return new StudentBean.StudentBeanBuilder();
        }
    
        private StudentBean() {
        }
    
        public String getName() {
            return this.name;
        }
    
        public int getAge() {
            return this.age;
        }
    
        public StudentBean setName(String name) {
            this.name = name;
            return this;
        }
    
        public StudentBean setAge(int age) {
            this.age = age;
            return this;
        }
    
        public boolean equals(Object o) {
            if (o == this) {
                return true;
            } else if (!(o instanceof StudentBean)) {
                return false;
            } else {
                StudentBean other = (StudentBean)o;
                if (!other.canEqual(this)) {
                    return false;
                } else {
                    Object this$name = this.getName();
                    Object other$name = other.getName();
                    if (this$name == null) {
                        if (other$name == null) {
                            return this.getAge() == other.getAge();
                        }
                    } else if (this$name.equals(other$name)) {
                        return this.getAge() == other.getAge();
                    }
    
                    return false;
                }
            }
        }
    
        protected boolean canEqual(Object other) {
            return other instanceof StudentBean;
        }
    
        public int hashCode() {
            int PRIME = true;
            int result = 1;
            Object $name = this.getName();
            int result = result * 59 + ($name == null ? 43 : $name.hashCode());
            result = result * 59 + this.getAge();
            return result;
        }
    
        public String toString() {
            return "StudentBean(name=" + this.getName() + ", age=" + this.getAge() + ")";
        }
    
        public static class StudentBeanBuilder {
            private String name;
            private int age;
    
            StudentBeanBuilder() {
            }
    
            public StudentBean.StudentBeanBuilder name(String name) {
                this.name = name;
                return this;
            }
    
            public StudentBean.StudentBeanBuilder age(int age) {
                this.age = age;
                return this;
            }
    
            public StudentBean build() {
                return new StudentBean(this.name, this.age);
            }
    
            public String toString() {
                return "StudentBean.StudentBeanBuilder(name=" + this.name + ", age=" + this.age + ")";
            }
        }
    }
    

    最终生成类如上面一样,属性的 get、set 方法有了,并且支持链式调用,而且还是builder模式。

    八、 更多其他Lombok注解的使用

    参考

    https://blog.csdn.net/xiaojin21cen/article/details/83478929


    作者:不敲代码的攻城狮
    出处:https://www.cnblogs.com/leigq/
    任何傻瓜都能写出计算机可以理解的代码。好的程序员能写出人能读懂的代码。

     
  • 相关阅读:
    高一下期末考试划水记
    BZOJ 1053
    积性函数与狄利克雷卷积(未完待更)
    Contest Hunter 3101
    POJ2689
    3.17爆零赛
    全概率公式
    矩阵快速幂
    模板练习
    _rqy's Code Style for OI
  • 原文地址:https://www.cnblogs.com/leigq/p/13406569.html
Copyright © 2020-2023  润新知