2017-05-05 22 views
0

我對使用垂直繼承或者組合進行簡單的OOP實現有第二個想法。我讀過很多,但我仍然很難下定決心。 ^^在特定上下文中的繼承與構造

我需要生成四個不同的報告:報價,發票,目錄和手冊: - 每個報告都有相同的頁眉和頁腳。 - 報價和發票包含具有不同數據的相同格式表。 - 小冊子和目錄與其他報告的結構不同,並且沒有表格。

我想在這裏提供OOP設計方面的幫助;我將介紹我的兩個想法(僞代碼),但任何反饋將不勝感激。 :)

繼繼承

class Report 
{ 
    method Header() 
    { 
     // Print the header 
    } 

    method Footer() 
    { 
     // Print the footer 
    } 
} 

class ReportTable 
{ 
    method Table() 
    { 
     // Print the table 
    } 
} 

class Quote extends ReportTable 
{ 
    method BuildReport() 
    { 
     call Header() 

     call Table() 
     // Print some more quote stuff 

     call Footer() 
    } 
} 

class Invoice extends ReportTable 
{ 
    method BuildReport() 
    { 
     call Header() 

     call Table() 
     // Print some more invoice stuff 

     call Footer() 
    } 
} 

class Catalogue extends Report 
{ 
    method BuildReport() 
    { 
     call Header() 

     // Print catalogue stuff 

     call Footer() 
    } 
} 

class Brochure extends Report 
{ 
    method BuildReport() 
    { 
     call Header() 

     // Print brochure stuff 

     call Footer() 
    } 
} 

以下組成的表功能

class Report 
{ 
    method Header() 
    { 
     // Print the header 
    } 

    method Footer() 
    { 
     // Print the footer 
    } 
} 

class Table 
{ 
    method Table() 
    { 
     // Print the table 
    } 
} 

class Quote extends Report 
{ 
    property table 

    constructor Quote(Table table) 
    { 
     self.table = table 
    } 

    method BuildReport() 
    { 
     call Header() 

     call self.table.Table() 
     // Print some more quote stuff 

     call Footer() 
    } 
} 

class Invoice extends Report 
{ 
    property table 

    constructor Invoice(Table table) 
    { 
     self.table = table 
    } 

    method BuildReport() 
    { 
     call Header() 

     call self.table.Table() 
     // Print some more invoice stuff 

     call Footer() 
    } 
} 

class Catalogue extends Report 
{ 
    method BuildReport() 
    { 
     call Header() 

     // Print catalogue stuff 

     call Footer() 
    } 
} 

class Brochure extends Report 
{ 
    method BuildReport() 
    { 
     call Header() 

     // Print brochure stuff 

     call Footer() 
    } 
} 

非常感謝! :)

回答

1

這可能是一個宗教問題。無論哪種方式都可以工作,並且從一個到另一個重構都很容易。標準邏輯表示贊成組合而不是繼承,但是按照正確的方式行事。