Created
August 16, 2017 03:58
-
-
Save mnadeem/5fe054e85703e84d7e390b21d8446968 to your computer and use it in GitHub Desktop.
Builder Pattern With Fluent Interface
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
/** | |
* @author Nadeem Mohammad | |
*/ | |
public class RestUrl { | |
private String url; | |
private RestUrl(String url) { | |
this.url = url; | |
} | |
public String get() { | |
return url; | |
} | |
public static BaseUrl builder() { | |
return new Builder(); | |
} | |
public static class Builder implements BaseUrl, RequestUri, UrlParam, Build { | |
private static final String SLASH = "/"; | |
public static final String BRACE_OPEN = "{"; | |
public static final String BRACE_CLOSE = "}"; | |
private StringBuilder buffer; | |
public Builder () { | |
this.buffer = new StringBuilder(); | |
} | |
@Override | |
public Builder baseUrl(String baseUrl) { | |
if (baseUrl.endsWith("/")) { | |
baseUrl = baseUrl.substring(0, baseUrl.length() - 1); | |
} | |
buffer.append(baseUrl); | |
return this; | |
} | |
@Override | |
public Builder requestUri(String requestUri) { | |
if (!requestUri.startsWith(SLASH)) { | |
requestUri = SLASH + requestUri; | |
} | |
buffer.append(requestUri); | |
return this; | |
} | |
@Override | |
public UrlParam urlParam(String urlParam) { | |
buffer.append(urlParam); | |
return this; | |
} | |
@Override | |
public UrlParam urlPlaceHolderParam(String urlParam) { | |
buffer.append(BRACE_OPEN).append(urlParam).append(BRACE_CLOSE); | |
return this; | |
} | |
@Override | |
public RestUrl build() { | |
return new RestUrl(buffer.toString()); | |
} | |
} | |
interface BaseUrl { | |
RequestUri baseUrl(String baseUrl); | |
} | |
interface RequestUri { | |
UrlParam requestUri(String requestUri); | |
} | |
interface UrlParam { | |
UrlParam urlParam(String urlParam); | |
UrlParam urlPlaceHolderParam(String urlParam); | |
RestUrl build(); | |
} | |
interface Build { | |
RestUrl build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment