优点
- 代码简洁
- 可读性强
- 一种可借鉴的编程思想
应用场景
需要单独明确的代码块处理需求,
简单实例
import java.util.HashMap;
import java.util.Map;
/**
* 员工信息链式写法
* */
public class MemberInfoChain {
private String id;
private String name;
private Map<String, Object> baseInfo;
private String otherInfo;
public MemberInfoChain setId(String id) {
this.id = id;
return this;
}
public MemberInfoChain setName(String name) {
this.name = name;
return this;
}
public MemberInfoChain setBaseInfo(String key, Object value) {
if(this.baseInfo == null){
this.baseInfo = new HashMap<>();
}
this.baseInfo.put(key,value);
return this;
}
public MemberInfoChain setOtherInfo(String otherInfo) {
this.otherInfo = new String(new StringBuffer().append(this.otherInfo).append(otherInfo));
return this;
}
@Override
public String toString() {
return "MemberInfoChain{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", baseInfo=" + baseInfo +
", otherInfo='" + otherInfo + '\'' +
'}';
}
}
import java.util.Map;
/**
* 员工信息一般写法
*/
public class MemberInfo {
private String id;
private String name;
private Map<String, Object> baseInfo;
private String otherInfo;
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setBaseInfo(Map<String, Object> baseInfo) {
this.baseInfo = baseInfo;
}
public void setOtherInfo(String otherInfo) {
this.otherInfo = otherInfo;
}
@Override
public String toString() {
return "MemberInfo{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", baseInfo=" + baseInfo +
", otherInfo='" + otherInfo + '\'' +
'}';
}
}
import java.util.HashMap;
import java.util.Map;
/**
* 测试类
*/
public class TestMain {
public static void main(String[] args) {
String id = "1";
String name = "lili";
int age = 21;
String memberLevel = "VIP";
String otherInfo1 = "other Info1";
String otherInfo2 = "other Info2";
String otherInfo3 = "other Info3";
MemberInfo memberInfo = new MemberInfo();
Map<String, Object> map = new HashMap<>();
map.put("age", age);
map.put("memberLevel", memberLevel);
StringBuffer sb = new
StringBuffer().append(otherInfo1).append(otherInfo2).append(otherInfo3);
String otherInfo = new String(sb);
memberInfo.setId(id);
memberInfo.setName(name);
memberInfo.setBaseInfo(map);
memberInfo.setOtherInfo(otherInfo);
MemberInfoChain memberInfoChain = new MemberInfoChain();
memberInfoChain.setId(id)
.setName(name)
.setBaseInfo("age",age)
.setBaseInfo("memberLevel",memberLevel)
.setOtherInfo(otherInfo1)
.setOtherInfo(otherInfo2)
.setOtherInfo(otherInfo3);
System.out.println(memberInfo);
System.out.println(memberInfoChain);
}
}
基于实际开发,在logback,极光推送l链式编程的理解