Java interfaces and composition
An interface declares operations that implementing classes provide. A Report receives a Formatter rather than constructing one hard-coded implementation internally.
Java
interface Formatter {
String format(String text);
}
class BracketFormatter implements Formatter {
public String format(String text) { return "[" + text + "]"; }
}
class Report {
private final Formatter formatter;
Report(Formatter formatter) { this.formatter = formatter; }
String render() { return formatter.format("Ready"); }
}
class Main {
public static void main(String[] args) {
Report report = new Report(new BracketFormatter());
System.out.println(report.render());
}
}