delegation/README.md
To allow an object to delegate responsibility for a task to another helper object.
Real-world example
In a restaurant, the head chef delegates tasks to sous-chefs: one manages grilling, another handles salads, and a third is in charge of desserts. Each sous-chef specializes in their area, allowing the head chef to focus on overall kitchen management. This mirrors the Delegation design pattern, where a main object delegates specific tasks to helper objects, each expert in their domain.
In plain words
Delegation is a design pattern where an object passes on a task to a helper object.
Wikipedia says
In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender). Delegation can be done explicitly, by passing the sending object to the receiving object, which can be done in any object-oriented language; or implicitly, by the member lookup rules of the language, which requires language support for the feature.
Sequence diagram
Let's consider a printing example.
We have an interface Printer and three implementations CanonPrinter, EpsonPrinter and HpPrinter.
public interface Printer {
void print(final String message);
}
@Slf4j
public class CanonPrinter implements Printer {
@Override
public void print(String message) {
LOGGER.info("Canon Printer : {}", message);
}
}
@Slf4j
public class EpsonPrinter implements Printer {
@Override
public void print(String message) {
LOGGER.info("Epson Printer : {}", message);
}
}
@Slf4j
public class HpPrinter implements Printer {
@Override
public void print(String message) {
LOGGER.info("HP Printer : {}", message);
}
}
The PrinterController can be used as a Printer by delegating any work handled by this interface to an object implementing it.
public class PrinterController implements Printer {
private final Printer printer;
public PrinterController(Printer printer) {
this.printer = printer;
}
@Override
public void print(String message) {
printer.print(message);
}
}
In the client code, printer controllers can print messages differently depending on the object they're delegating that work to.
public class App {
private static final String MESSAGE_TO_PRINT = "hello world";
public static void main(String[] args) {
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);
}
}
Program output:
HP Printer:hello world
Canon Printer:hello world
Epson Printer:hello world
Benefits:
Trade-offs: