常用Lombok的都知道里面有一个@Builder注解很好用,但是这个注解的原理是什么呢,这里简单模拟一下。
这里使用了设计模式中的建造者模式。
package com.example.demoboot;
import java.io.Serializable;
/**
* 数据源实例
*
* @author starsray
* @date 2021/11/20
*/
public class DatasourceInstance implements Serializable {
private String type;
private String name;
private String username;
private String password;
private String url;
private String driver;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
private DatasourceInstance(Builder builder) {
this.type = builder.type;
this.name = builder.name;
this.username = builder.username;
this.password = builder.password;
this.url = builder.url;
this.driver = builder.driver;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String type;
private String name;
private String username;
private String password;
private String url;
private String driver;
public Builder type(String type) {
this.type = type;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder username(String username) {
this.username = username;
return this;
}
public Builder password(String password) {
this.password = password;
return this;
}
public Builder url(String url) {
this.url = url;
return this;
}
public Builder driver(String driver) {
this.driver = driver;
return this;
}
public DatasourceInstance build() {
return new DatasourceInstance(this);
}
}
}