Created
February 15, 2014 19:03
-
-
Save emilong/9023691 to your computer and use it in GitHub Desktop.
A suggested builder-style bean pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Traditional bean */ | |
public class Bean { | |
private String foo; | |
private String bar; | |
private int baz; | |
public Bean() { | |
} | |
public Bean(String foo, String bar, int baz) { | |
this.foo = foo; | |
this.bar = bar; | |
this.baz = baz; | |
} | |
public String getFoo() { | |
return foo; | |
} | |
public void setFoo(String foo) { | |
this.foo = foo; | |
} | |
public String getBar() { | |
return bar; | |
} | |
public void setBar(String bar) { | |
this.bar = bar; | |
} | |
public int getBaz() { | |
return baz; | |
} | |
public void setBaz(int baz) { | |
this.baz = baz; | |
} | |
public static void exampleUsage() { | |
Bean bean1 = new Bean("is this foo or bar?", "I think this is bar", 123); | |
Bean bean2 = new Bean(); | |
bean2.setFoo("I know this is foo"); | |
bean2.setBar("and this is bar, but this sure is verbose"); | |
bean2.setBaz(123); | |
} | |
} | |
/* Builder-style bean */ | |
public class Bean { | |
private String foo; | |
private String bar; | |
private int baz; | |
public String foo() { | |
return foo; | |
} | |
public Bean foo(String foo) { | |
this.foo = foo; | |
return this; | |
} | |
public String bar() { | |
return bar; | |
} | |
public Bean bar(String bar) { | |
this.bar = bar; | |
return this; | |
} | |
public int baz() { | |
return baz; | |
} | |
public Bean baz(int baz) { | |
this.baz = baz; | |
return this; | |
} | |
public static void exampleUsage() { | |
Bean bean = new Bean() | |
.foo("I know this is foo") | |
.bar("and I set bar compactly!") | |
.baz(123); | |
System.out.println("bean.foo = " + bean.foo()); | |
} | |
} | |
/* Hybrid Builder-style bean */ | |
public class Bean { | |
private String foo; | |
private String bar; | |
private int baz; | |
public String getFoo() { | |
return foo; | |
} | |
public Bean foo(String foo) { | |
this.foo = foo; | |
return this; | |
} | |
public String getBar() { | |
return bar; | |
} | |
public Bean bar(String bar) { | |
this.bar = bar; | |
return this; | |
} | |
public int getBaz() { | |
return baz; | |
} | |
public Bean baz(int baz) { | |
this.baz = baz; | |
return this; | |
} | |
public static void exampleUsage() { | |
Bean bean = new Bean() | |
.foo("I know this is foo") | |
.bar("and I set bar compactly!") | |
.baz(123); | |
System.out.println("bean.foo = " + bean.getFoo()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like the Builder approach. It's similar to Fluent API https://en.wikipedia.org/wiki/Fluent_interface#Java