Created
December 21, 2011 19:03
-
-
Save bpsm/1507228 to your computer and use it in GitHub Desktop.
An example of a pattern for constructing immutable objects using a fluent builder implemented as an inner class.
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
package innerclassbuilderexample; | |
/* | |
* An example of a pattern for constructing immutable | |
* objects using a fluent builder implemented as an | |
* inner class. | |
* | |
* Some boiler plate code can be saved if one is willing to give up | |
* fluency in the Builder's interface. | |
*/ | |
public class Point { | |
private int x; | |
private int y; | |
public int getX() { | |
return x; | |
} | |
public int getY() { | |
return y; | |
} | |
public static Builder builder() { | |
return new Point().new Builder(); | |
} | |
/** Zero arg constructor is deliberately not public */ | |
Point() { | |
} | |
public class Builder { | |
public Point build() { | |
return Point.this; | |
} | |
public Builder setX(int x) { | |
Point.this.x = x; | |
return this; | |
} | |
public Builder setY(int y) { | |
Point.this.y = y; | |
return this; | |
} | |
/** Zero arg constructor is deliberately not public */ | |
Builder() { | |
} | |
} | |
/* | |
* A demonstration of usage. | |
* | |
* The constructed object (Point) is immutable (read-only). The | |
* builder that must be used to construct the Point is | |
* write-only. This forces a clear separation of object | |
* construction (writing) from object use (reading). | |
*/ | |
public static void main(String[] args) { | |
Point.Builder b = Point.builder(); | |
b.setX(1).setY(2); | |
Point p = b.build(); | |
System.err.println(p.getX() + p.getY()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment