我嘗試編寫一個裝飾器模式的簡單示例。省略在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