Created
November 14, 2016 21:24
-
-
Save rtoal/a4118f2be1c27dbb6a8b4953757db410 to your computer and use it in GitHub Desktop.
A pretty cool builder pattern I discovered in Java
This file contains hidden or 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
class Pager { | |
private int offset; | |
private int limit; | |
private Pager() {} | |
public static Pager withOffset(int offset) {return new Pager().offset(offset);} | |
public Pager offset(int offset) {this.offset = offset; return this;} | |
public int offset() {return this.offset;} | |
public static Pager withLimit(int limit) {return new Pager().limit(limit);} | |
public Pager limit(int limit) {this.limit = limit; return this;} | |
public int limit() {return this.limit;} | |
} | |
class PageTest { | |
public static void main(String[] args) { | |
Pager p1 = Pager.withOffset(5); | |
assert p1.offset() == 5; | |
assert p1.limit() == 0; | |
Pager p2 = Pager.withLimit(5); | |
assert p2.offset() == 0; | |
assert p2.limit() == 5; | |
Pager p3 = Pager.withLimit(5).offset(11); | |
assert p3.offset() == 11; | |
assert p3.limit() == 5; | |
Pager p4 = Pager.withOffset(5).limit(3); | |
assert p4.offset() == 5; | |
assert p4.limit() == 3; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment