Java fluent风格(转载)

转载:java Fluent风格

 

一.我们先写一个通常的,即不使用fluent风格

1.实体类

 1 package com.xbq.demo.stu;
 2 
 3 /**
 4  * @ClassName: Student 
 5  * @Description: TODO(学生实体类) 
 6  * @author xbq 
 7  * @date 2017-3-26 下午9:54:00 
 8  */
 9 public class Student {
10 
11     private String name;
12     private String address;
13     
14     public String getName() {
15         return name;
16     }
17     public void setName(String name) {
18         this.name = name;
19     }
20     public String getAddress() {
21         return address;
22     }
23     public void setAddress(String address) {
24         this.address = address;
25     }
26     
27     @Override
28     public String toString() {
29         return "Student [name=" + name + ", address=" + address + "]";
30     }
31 }

2.测试类

 1 package com.xbq.demo.stu;
 2 
 3 /**
 4  * @ClassName: Test 
 5  * @Description: TODO(测试学生实体,非 fluent风格) 
 6  * @author xbq 
 7  * @date 2017-3-26 下午9:55:34 
 8  */
 9 public class Test {
10 
11     public static void main(String[] args) {
12         Student student = new Student();
13         student.setName("张三");
14         student.setAddress("广东深圳");
15         System.out.println(student);
16     }
17 }

二.再写一个使用fluent风格的

1.实体类

 1 package com.xbq.demo;
 2 
 3 /**
 4  * @ClassName: Student  
 5  * @Description: TODO(学生实体类) 
 6  * @author xbq 
 7  * @date 2017-3-26 下午7:56:20 
 8  */
 9 public class Student {
10 
11     private String name;
12     private String address;
13     
14     // 设置name的值,并且返回实体
15     public Student setName(String name){
16         this.name = name;
17         return this;
18     }
19     
20     // 设置address的值,并且返回实体
21     public Student setAddress(String address){
22         this.address = address;
23         return this;
24     }
25     
26     public String getName() {
27         return name;
28     }
29     public String getAddress() {
30         return address;
31     }
32     
33     // 返回学生实体,可以做成单例
34     public static Student build(){
35         return new Student();
36     }
37     
38     @Override
39     public String toString() {
40         return "Student [name=" + name + ", address=" + address + "]";
41     }
42 }

2.测试类

 1 package com.xbq.demo;
 2 
 3 /**
 4  * @ClassName: Test 
 5  * @Description: TODO(测试学生实体, fluent风格) 
 6  * @author xbq 
 7  * @date 2017-3-26 下午9:59:22 
 8  */
 9 public class Test {
10 
11     public static void main(String[] args) {
12         Student student = Student.build().setName("李四").setAddress("广东广州");
13         System.out.println(student.getName());
14     }
15 }

 

posted @ 2018-12-03 19:43  donfaquir  阅读(782)  评论(0编辑  收藏  举报