본문 바로가기

emotional developer/detect-pattern

Achieving Immutability with Builder Design Pattern

http://java.dzone.com/articles/immutability-with-builder-design-pattern?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+javalobby/frontpage+(Javalobby+/+Java+Zone)


Immutable User

01.public class ImmutableUser {
02. 
03.private final String username;
04.private final String password;
05.private final String firstname;
06.private final String lastname;
07.private final String email;
08.private final Date creationDate;
09. 
10.private ImmutableUser(UserBuilder builder) {
11.this.username = builder.username;
12.this.password = builder.password;
13.this.creationDate = builder.creationDate;
14.this.firstname = builder.firstname;
15.this.lastname = builder.lastname;
16.this.email = builder.email;
17.}
18. 
19.public static class UserBuilder {
20.private final String username;
21.private final String password;
22.private final Date creationDate;
23.private String firstname;
24.private String lastname;
25.private String email;
26. 
27.public UserBuilder(String username, String password) {
28.this.username = username;
29.this.password = password;
30.this.creationDate = new Date();
31.}
32. 
33.public UserBuilder firstName(String firsname) {
34.this.firstname = firsname;
35.return this;
36.}
37. 
38.public UserBuilder lastName(String lastname) {
39.this.lastname = lastname;
40.return this;
41.}
42. 
43.public UserBuilder email(String email) {
44.this.email = email;
45.return this;
46.}
47. 
48.public ImmutableUser build() {
49.return new ImmutableUser(this);
50.}
51. 
52.}
53. 
54.public String getUsername() {
55.return username;
56.}
57. 
58.public String getPassword() {
59.return password;
60.}
61. 
62.public String getFirstname() {
63.return firstname;
64.}
65. 
66.public String getLastname() {
67.return lastname;
68.}
69. 
70.public String getEmail() {
71.return email;
72.}
73. 
74.public Date getCreationDate() {
75.return new Date(creationDate.getTime());
76.}
77. 
78.}

 

You should also check the invariants in the build method and throw in an IllegalStateException if any attribute is invalid. This will ensure that the object is in a workable state once it is instantiated.

The client code will look like this :

1.public static void main(String[] args) {
2.ImmutableUser user = new ImmutableUser.UserBuilder("shekhar",
3."password").firstName("shekhar").lastName("gulati")
4..email("shekhargulati84@gmail.com").build();
5.}
반응형

'emotional developer > detect-pattern' 카테고리의 다른 글

채번방식?  (0) 2014.01.24
TDD를통해의존성줄여보자.  (2) 2007.12.05
Refactoring Workbook  (0) 2007.11.18