我尝试编写一个装饰器模式的简单示例。省略在Java儿童中使用构造函数
我有一个Printable
接口,一个具体的类印刷和抽象类的装饰:
// 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();
}
}
请注意,我用抽象PrinterDecorator
构造。 因此,我写了两个具体的装饰器来打印要打印的基本内容的页眉和页脚。这里页脚装饰是:
class FooterPrinterDecorator extends PrinterDecorator {
/*public FooterPrinterDecorator(Printable p) {
super(p);
}*/
public void print() {
super.print();
System.out.println("Footer");
}
}
在这里,我想PrinterDecorator
孩子们不要重新声明父类的构造。但我得到了一个错误,如果我与上述评论运行:
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
而且我试图手动写在父母装饰默认构造函数。在这种情况下,编译器给了我同样的错误,但在其他方面(指望它不带参数的构造函数,即使我给Printable
作为参数的构造函数的调用:
Printable one = new FooterPrinterDecorator(new DisplayPrinter());
所以,我可以省略在其子女的父或母,构造的重复?
@ brso05,是的,我试过了。但它不能解决问题。我更新了错误消息和对构造函数的调用。 – Bogdan