2017-05-05 43 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

这可能是一个宗教问题。无论哪种方式都可以工作,并且从一个到另一个重构都很容易。标准逻辑表示赞成组合而不是继承,但是按照正确的方式行事。