Delegating pattern using lambda

Delegating pattern

In software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as an inheritance. In delegation, an object handles a request by delegating to a second object. A delegate is a helper object, but with the original context.

To demonstrate the necessity of delegation of execution, let’s look at an example.

package delegation

public class LazyTest {

	private static int calculate(int x) {
		System.out.println("Called ....");
		return x * 2;
	}


	public static void main(String[] args) {

		int x = 5;
		int temp = calculate(4);
		if (x > 5 && temp >= 4) {
			System.out.println("Path 1");
		} else {
			System.out.println("Path 2");
		}
	}
}

If we run the code, we can observe that the method “calculate” is only called once, and its output is never used.

If we consider other languages like Scala, the execution can be deferred as needed by using the lazy keyword, for example, lazy int temp = calculate(4).

Unfortunately, Java doesn’t support the lazy keyword. We can achieve this by using Lambda.

Lambda can be used to delegate method calls when execution is required.

Let us Design it

package delegation


import java.util.function.Supplier;


public class Lazy<T> {
	
	private T instance;
	private Supplier<T> supplier;


	public Lazy(Supplier<T> supplier) {
		this.supplier = supplier;
	}


	public T get() {
		if (instance == null) {
			instance = supplier.get();
			supplier = null;
		}
		return instance;
	}
}

;

Now let us test the same

package delegation


public class LazyTest {


	private static int calculte(int x) {
		System.out.println("Called ....");
		return x * 2;
	}


	public static void main(String[] args) {
		int x = 5;
		final Lazy<Integer> temp = new Lazy<Integer>(()-> calculte(4));
		if (x > 5 && temp.get() >= 4) {
			System.out.println("Path 1");
		} else {
			System.out.println("Path 2");
		}
	}
}

;

Test 1 – If you run the code right now, you’ll notice that the method calculate is not being called.

Test 2 – Change the value of x to 15 and then run the code. The function calculate is now only run once because the temp is assessed within it, which is fine.

Previous
Next