Created
June 9, 2020 09:22
-
-
Save SiAust/5e91d0b0960134973dd241fa15e0fe7a to your computer and use it in GitHub Desktop.
Example of a Strategy pattern that could be used for API calls.
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
| // Strategy design pattern with API requests, example. | |
| class ApiRequestSender { | |
| ApiRequestMethod apiRequestMethod; | |
| public static void main(String[] args) { | |
| ApiRequestSender apiCategoriesRequest = new ApiRequestSender(); | |
| apiCategoriesRequest.setApiRequestMethod(new CategoriesRequest()); | |
| System.out.println(apiCategoriesRequest.sendRequest("www.spotify.com/endpoint/categories")); | |
| ApiRequestSender apiNewRequest = new ApiRequestSender(); | |
| apiNewRequest.setApiRequestMethod(new ApiRequestNew()); | |
| System.out.println(apiNewRequest.sendRequest("www.spotify.com/endpoint/new")); | |
| } | |
| public void setApiRequestMethod(ApiRequestMethod apiRequestMethod) { | |
| this.apiRequestMethod = apiRequestMethod; | |
| } | |
| public String sendRequest(String request) { | |
| return this.apiRequestMethod.send(request); | |
| } | |
| } | |
| interface ApiRequestMethod { | |
| String send(String request); | |
| } | |
| class CategoriesRequest implements ApiRequestMethod { | |
| @Override | |
| public String send(String request) { | |
| return "Categories JSON"; | |
| } | |
| } | |
| class ApiRequestNew implements ApiRequestMethod { | |
| @Override | |
| public String send(String request) { | |
| return "New JSON"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment