2017-04-20 22 views
1

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

所以,我可以省略在其子女的父或母,構造的重複?

+0

@ brso05,是的,我試過了。但它不能解決問題。我更新了錯誤消息和對構造函數的調用。 – Bogdan

回答

2

你不能;如果你的父類沒有默認的構造函數,那麼每個孩子必須實現一個調用父類的構造函數。這是爲了保持封裝,並且因爲構造函數不像方法那樣繼承。

你能做什麼,不過,是有一種方法,而不是在PrinterDecorator構造:

abstract class PrinterDecorator implements Printable { 
    private Printable printer; 

    public void setDecorator(Printable p) { 
    printer = p; 
    } 

    public void print() { 
    if (printer != null) 
     printer.print(); 
    } 
} 

現在你的孩子並不需要亂用這種方法,他們將繼承原樣。

+0

這是一個正確的答案,並且這種技術可以節省編寫樣板構造函數的工作。雖然它引入了時間耦合:'setDecorator'必須在正確的時間恰好調用一次。如果有人忘記叫它,它會導致錯誤。如果有人更多次地自稱,這也會導致醜陋的情況。所以我的建議是:考慮使用這些樣板構造函數(即使您的IDE生成它),並使打印機領域'最終'。 – pcjuzer

1

答案是否定的。構造函數不是在java中繼承的。你看這個錯誤,因爲類FooterPrinterDecorator只默認的構造函數,它沒有參數(required: no arguments)。

Java Constructor Inheritance