Hi All,
Thanks again for reading my comments over internet.
I am trying to help java developers to know more about implementations and configurations using Java or JBoss Midleware technologies.
Now i would like to show a simple implementation pattern: Builder.
So, let's see the example:
1 - Simple Person class
/**
* Person simple class information
*
* @author alvesfred
*
*/
public class SimplePerson implements Serializable {
/**
* serial
*/
private static final long serialVersionUID = -978731152684129660L;
private String name;
private int age;
private boolean male;
private boolean married;
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 boolean isMale() {
return male;
}
public void setMale(boolean male) {
this.male = male;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
}
2 - Builder Pattern
/**
* Builder pattern
*
* @author alvesfred
*
*/
public abstract class Builder<T> {
/**
* Build
*
* @return
*/
public abstract T build();
}
/**
* Builder pattern class
*
* @author alvesfred
*
*/
public class Person {
private final String name;
private final int age;
private final boolean male;
private final boolean married;
public Person(PersonBuilder pfb) {
this.name = pfb.name;
this.age = pfb.age;
this.male = pfb.male;
this.married = pfb.married;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public boolean isMale() {
return male;
}
public boolean isMarried() {
return married;
}
/**
* Builder class sample
*
* @author alvesfred
*
*/
public static class PersonBuilder extends Builder<Person> {
private final String name;
private int age;
private boolean male;
private boolean married;
public PersonBuilder(String name) {
this.name = name;
}
public PersonBuilder defineAge(int age) {
this.age = age;
return this;
}
public PersonBuilder defineMale(boolean male) {
this.male = male;
return this;
}
public PersonBuilder defineMarried(boolean married) {
this.married = married;
return this;
}
public Person build() {
return new Person(this);
}
}
@Override
public String toString() {
return "[PERSON] " + name
+ " - [Age] " + age
+ " - [Male?] " + male
+ " - [Married] " + married;
}
/**
* Main
*
* @param args
*/
public static void main(String[] args) {
Person p = new PersonBuilder("Fred")
.defineAge(38)
.defineMale(true)
.defineMarried(true)
.build();
System.out.println(p);
}
}
A few months ago i see this important API, and i like it so much!
Lombok API is very interesting...have fun!
https://projectlombok.org/
[IMHO] for @Data annotation using lombok, I just recommend override equals and hashCode methods to use HashCodeBuilder and EqualsBuilder (Apache Commons).
Thanks a lot and see you next time!
"Move to Canada/Vancouver - it is my dream! Java/JEE/Middleware development is my work and i love it so much!"
No comments:
Post a Comment