Builder design pattern

PHOTO EMBED

Sun May 08 2022 07:04:17 GMT+0000 (Coordinated Universal Time)

Saved by @suhasjoshi #designpattern #builderdesignpattern

/**
 * 
 */
package com.design.pattern.builder;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * This class helps to call the provided web address with common headers. <br />
 * Extra headers can be added with proper request model while calling the
 * endpoint
 * 
 * @author s0j0180
 *
 */
public class WebClient {

	private Map<String, String> headers;
	private URI endpoint;
	private Boolean isAuthRequired;

	private WebClient(WebClientBuilder builder) {
		this.headers = builder.headers;
		this.endpoint = builder.endpoint;
		this.isAuthRequired = builder.isAuthRequired;

	}

	
	
	public Map<String, String> getHeaders() {
		return headers;
	}

	public URI getEndpoint() {
		return endpoint;
	}

	public Boolean getIsAuthRequired() {
		return isAuthRequired;
	}



	public static class WebClientBuilder {
		private Map<String, String> headers = new HashMap<>();
		private URI endpoint;
		private Boolean isAuthRequired;

		public static WebClientBuilder builder() {
			return new WebClientBuilder();
		}

		public WebClientBuilder withHeaders(Map<String, String> headers) {
			if (headers != null) {
				this.headers.putAll(headers);
			}
			return this;
		}

		public WebClientBuilder withEndPoint(URI endpoint) {
			if (endpoint != null) {
				this.endpoint = endpoint;
			}
			return this;
		}
		
		public WebClientBuilder withIsAuthRequired(Boolean isAuthRequired) {
			this.isAuthRequired = isAuthRequired;
			return this;
		}
		
		public WebClient build() {
			return new WebClient(this);
		}

	}

	public String call(String request) {
		// Call external service and return response
		return  new StringBuilder().append("Successfully called UIR: ").append(this.endpoint).append(", with Request: ").append(request).toString();
	}

	//Test builder
	public static void main(String[] args) throws URISyntaxException {
		
		WebClient client = WebClientBuilder.builder().withEndPoint(new URI("http://localhost:8080/demo")).withHeaders(null).withIsAuthRequired(true).build();
		System.out.println(client.call("my Request"));
		
	}
	
}
content_copyCOPY

Example of Builder design pattern