-
組合:將對(duì)象組合成樹形結(jié)構(gòu)以表示“部分-整體”的層次結(jié)構(gòu)垫桂。組合模式使得用戶對(duì)單個(gè)對(duì)象和組合對(duì)象的使用具有一致性霞溪。
-
使用場景:將多個(gè)對(duì)象組合在一起進(jìn)行操作,常用于表示樹形結(jié)構(gòu)中沾歪,例如二叉樹等
注解:當(dāng)前組合結(jié)構(gòu)的示意圖如下:一個(gè)??型圖
代碼:
//獲取書籍的瀏覽量和銷售量
public interface Statistics {
int getBrowseCount(); /
int getSalesCount();
}
//計(jì)算機(jī)類書籍
public class ComputerBookStatistics implements Statistics {
@Override
public int getBrowseCount() {
int browseCount = 0;
List<String> allComputerBooks = getAllComputerBooks();
for (String computerBook : allComputerBooks) {
browseCount += getBrowseCount(computerBook);
}
return browseCount;
}
@Override
public int getSalesCount() {
int saleCount = 0;
List<String> allComputerBooks = getAllComputerBooks();
for (String computerBook : allComputerBooks) {
saleCount += getSaleCount(computerBook);
}
return saleCount;
}
}
//醫(yī)學(xué)類書籍
public class MedicalBookStatistics implements Statistics {
@Override
public int getBrowseCount() {
int browseCount = 0;
List<String> allMedicalBooks = getAllMedicalBooks();
for (String medicalBook : allMedicalBooks) {
browseCount += getBrowseCount(medicalBook);
}
return browseCount;
}
@Override
public int getSalesCount() {
int saleCount = 0;
List<String> allMedicalBooks = getAllMedicalBooks();
for (String medicalBook : allMedicalBooks) {
saleCount += getSaleCount(medicalBook);
}
return saleCount;
}
}
問題:獲取科技類書籍的銷售量漂彤,瀏覽量?
public class TechnicalStatistics implements Statistics {
private List<Statistics> statistics = new ArrayList<Statistics>();
public TechnicalStatistics() {
statistics.add(new ComputerBookStatistics());
statistics.add(new MedicalBookStatistics());
}
@Override
public int getBrowseCount() {
int browseCount = 0;
for (Statistics s : statistics) {
browseCount += s.getBrowseCount();
}
return browseCount;
}
@Override
public int getSalesCount() {
int saleCount = 0;
for (Statistics s : statistics) {
saleCount += s.getBrowseCount();
}
return saleCount;
}
}
問題:統(tǒng)計(jì)所有書籍的瀏覽量和銷售量的辦法灾搏?
public class AllStatistics implements Statistics {
private List<Statistics> statistics = new ArrayList<Statistics>();
public AllStatistics() {
statistics.add(new NovelStatistics());
statistics.add(new TechnicalStatistics());
}
@Override
public int getBrowseCount() {
int browseCount = 0;
for (Statistics s : statistics) {
browseCount += s.getBrowseCount();
}
return browseCount;
}
@Override
public int getSalesCount() {
int saleCount = 0;
for (Statistics s : statistics) {
saleCount += s.getBrowseCount();
}
return saleCount;
}
}
使用:
new TechnicalStatistics().getBrowseCount(); //獲取科技類書籍瀏覽量
new AllStatistics().getSalesCount(); //獲取所有書籍的總銷量
挫望。。狂窑。媳板。