bridge pattern重構(gòu)report
我們要實(shí)現(xiàn)三個(gè)功能:在
jsp
頁面上生成報(bào)表(包括一個(gè)表和一個(gè)圖)、生成
pdf
報(bào)表和
excel
報(bào)表。
原來的代碼雖然已經(jīng)實(shí)現(xiàn)了這些功能,但每個(gè)類的功能不明確,而且存在大量重復(fù)代碼。于是想到用設(shè)計(jì)模式來解決這個(gè)問題。起初想用裝飾模式(
Decorator Pattern
),但經(jīng)過分析,發(fā)現(xiàn)裝飾模式適合于那種需要把多個(gè)功能動態(tài)組合在一起的情況。但對于一個(gè)
report
,我們并不需要它同時(shí)能生成
pdf
和
excel
(即不是多個(gè)功能的組合)。
橋梁模式(
Bridge Pattern
)才是最適合的。橋梁模式的用意是
"
將抽象化(
Abstraction
)與實(shí)現(xiàn)化(
Implementation
)脫耦,使得二者可以獨(dú)立地變化
"
。(
According to GoF, the Bridge Pattern is intended to "Decouple an abstraction from its implementation so that the two can vary independently"
)

類名 | 功能 | 角色 |
AbstractionReport | 所有功能報(bào)表的父類 | 抽象化(Abstraction) |
PdfReport | 生成pdf報(bào)表文件 | 修正抽象化 (Refined Abstraction) |
ExcelReport | 生成excel報(bào)表文件 | 修正抽象化 |
JspReport | 在jsp中調(diào)用,生成報(bào)表 | 修正抽象化 |
ImplementorReport | 所有數(shù)據(jù)報(bào)表的父類 | 實(shí)現(xiàn)化(Implementor) |
NetworkPerformanceReport | 網(wǎng)絡(luò)設(shè)備性能報(bào)表 | 具體實(shí)現(xiàn)化 (Concrete Implementor) |
ServerPerformanceReport | 服務(wù)器性能報(bào)表 | 具體實(shí)現(xiàn)化 |
PortTrafficReport | 接口流量報(bào)表 | 具體實(shí)現(xiàn)化 |
AbstractionReport的功能是生成pdf或excel文件,而ImplementorReport的功能是收集數(shù)據(jù),為生成報(bào)表作準(zhǔn)備。
AbstractionReport的子類相對固定,因?yàn)槲覀儸F(xiàn)在只要實(shí)現(xiàn)三個(gè)功能,當(dāng)然,如果以后還想再實(shí)現(xiàn)其他功能,比如生成txt報(bào)表或html報(bào)表,我們還能再擴(kuò)展,增加兩個(gè)類TxtReport和HtmlReport即可實(shí)現(xiàn)。
ImplementorReport的子類就比較多了,列出的只是其中三個(gè)。
任意一個(gè)AbstractionReport與ImplementorReport的組合都能有不同的功能。有了以上的各個(gè)類,我們就能生成各種各樣的報(bào)表,比如我們要生成一個(gè)“網(wǎng)絡(luò)設(shè)備性能”的pdf報(bào)表文件,就這么寫:
?????? AbstractionReport report = new PdfReport(new NetworkPerformanceReport());???????
?????? report.createReport();
生成excel報(bào)表文件:
?????? AbstractionReport report = new ExcelReport(new NetworkPerformanceReport());???????
?????? report.createReport();
生成“服務(wù)器性能報(bào)表”pdf報(bào)表文件:
?????? AbstractionReport report = new PdfReport(new ServerPerformanceReport());???????
?????? report.createReport();
生成“服務(wù)器性能報(bào)表”excel報(bào)表文件:
??? ??? AbstractionReport report = new ExcelReport(new ServerPerformanceReport());???????
?????? report.createReport();