Delegation Pattern and The By Keyword

Posted By : Mohd Altaf | 18-Mar-2024

Java java microservices Java Virtual Machine

Loading...

The delegation pattern is a technique where an object expresses a certain behavior to the outside but simultaneously delegates responsibility for implementing that behavior to an associated object.

Let's understand this with the help of an example:
Let's say we want a printer. And a printer does what it is supposed to do. Let's create an interface to show this behavior.

interface Printer {
 void print(final String message);
}

Also, Read Saving Files To System in Spring Boot

Now it does not matter which printer prints this.

So let's say we have Three Printers(Canon, Epson, and HP) . Whichever printer is available or has ink prints the text. Now all of them are of type printers so all three will implement the Printer interface.

class CanonPrinter implements Printer {
 @Override
 public void print(String message) {
 System.out.println("Canon Printer : "+message );
 }
}

class EpsonPrinter implements Printer {
 @Override
 public void print(String message) {
 System.out.println("Epson Printer : {}"+message);
 }
}

class HpPrinter implements Printer {
 @Override
 public void print(String message) {
 System.out.println("HP Printer : {}" + message);
 }
}

Let's say you want to use the HP Printer to print hello world. You would get that done by creating an object of type HpPrinter.

public class Main {
 public static void main(String args[]){
 final String MESSAGE_TO_PRINT = "hello world";
 var printer = new HpPrinter();
 printer.print(MESSAGE_TO_PRINT);
 }
}

If in the future you want to swap the usage of this HP Printer since there is no ink and you need to use the Epson Printer, you'll need to change the implementation to Epson in all the places where Hp was used so instead you use a controller. The work of this controller is to supply a printer that gives you the output.

Also, Read Featuring ngxTranslate To Implement Translation In Angular

class PrinterController implements Printer {

 private final Printer printer;

 public PrinterController(Printer printer) {
 this.printer = printer;
 }

 @Override
 public void print(String message) {
 printer.print(message);
 }
}

The main method will change like so

public class Main {

 public static void main(String args[]){
 final String MESSAGE_TO_PRINT = "hello world";

 var hpPrinterController = new PrinterController(new HpPrinter());
 var canonPrinterController = new PrinterController(new CanonPrinter());
 var epsonPrinterController = new PrinterController(new EpsonPrinter());

 hpPrinterController.print(MESSAGE_TO_PRINT);
 canonPrinterController.print(MESSAGE_TO_PRINT);
 epsonPrinterController.print(MESSAGE_TO_PRINT);
 }
}

Now the PrinterController decides which printer to use to print. In other words, itdelegates the responsibility from the user to the printer controller. This is known as the delegation pattern.