I try to write a simple example of the decorator pattern.
I have a Printable
interface, a concrete classes for printing and abstract class for decorator:
// for all objects that can be printed
interface Printable {
public void print();
}
// classes for decorating
class DisplayPrinter implements Printable {
public void print() {
System.out.println("Print to the display");
}
}
class PaperPrinter implements Printable {
public void print() {
System.out.println("Print to the paper");
}
}
// printer decorator for all possible decorators
abstract class PrinterDecorator implements Printable {
private Printable printer;
public PrinterDecorator(Printable p) {
printer = p;
}
public void print() {
if (printer != null)
printer.print();
}
}
Note that I use a constructor in abstract PrinterDecorator
.
So, then I wrote two concrete decorators for printing header and footer of the base content to be printed. Here the footer decorator is:
class FooterPrinterDecorator extends PrinterDecorator {
/*public FooterPrinterDecorator(Printable p) {
super(p);
}*/
public void print() {
super.print();
System.out.println("Footer");
}
}
Here I want the PrinterDecorator
children not to redeclare the parent constructor. But I get the next error if I run with comments above:
error: constructor FooterPrinterDecorator in class FooterPrinterDecorator cannot be applied to given types;
Printable one = new FooterPrinterDecorator(new DisplayPrinter());
^
required: no arguments
found: DisplayPrinter
reason: actual and formal argument lists differ in length
Also I tried to write default constructor in parent decorator manually. In that case the compiler gives me the same error, but in other context (it expect constructor without arguments even if I give the Printable
as a parameter. The call to the constructor:
Printable one = new FooterPrinterDecorator(new DisplayPrinter());
So, can I omit the duplication of the parent constructor in its children?