Java Design Pattern Analysis-Composite)

Source: Internet
Author: User

Reprinted please indicate the source: http://blog.csdn.net/guolin_blog/article/details/9153753

I heard that your company has recently launched a new E-book reading application. The market is very responsive. There are also book malls in the application, where users can choose their favorite books at will. Your company also attaches great importance to this project, increases investment, and decides to add more features to this application.

Well, you also know that you are not able to escape this attack. It wasn't long before your leader found you. He told you that the current application has made statistics on the page views and sales volume of each book, but now I want to increase the page views and sales volume of each book category, as well as the overall page views and sales volume of all books. I hope you can complete this function.

Of course, the jobs arranged by the leaders cannot be put off. You can only put your head on it, but fortunately this function does not look very complicated.

If you prefer novels, start with the statistical functions of novels. First, the getallnovels method can be used to obtain all novel names, and then the novel name is passed into the getbrowsecount method to obtain the book's page views. The new novel name is passed into the getsalecount method to obtain the book's sales volume. You can only use these known APIs!

public int getNovelsBrowseCount() {int browseCount = 0;List<String> allNovels = getAllNovels();for (String novel : allNovels) {browseCount += getBrowseCount(novel);}return browseCount;}public int getNovelsSaleCount() {int saleCount = 0;List<String> allNovels = getAllNovels();for (String novel : allNovels) {saleCount += getSaleCount(novel);}return saleCount;}

Soon you will write down the above two methods, both of which are obtained by getting all the novel names, then calculating the page views and sales volume of each novel one by one, and finally adding the results to get the total amount.

The novel statistics are complete, and then you start to do the statistical function of computer books, the Code is as follows:

public int getComputerBooksBrowseCount() {int browseCount = 0;List<String> allComputerBooks = getAllComputerBooks();for (String computerBook : allComputerBooks) {browseCount += getBrowseCount(computerBook);}return browseCount;}public int getComputerBooksSaleCount() {int saleCount = 0;List<String> allComputerBooks = getAllComputerBooks();for (String computerBook : allComputerBooks) {saleCount += getSaleCount(computerBook);}return saleCount;}

Except that the getallcomputerbooks method is used to obtain the names of all computer classes, other codes are basically the same as those in the novel statistics.

Now you have completed the statistical functions of two types of books, followed by books such as medicine, nature, history, law, politics, philosophy, tourism, and food. You suddenly realized the seriousness of some problems, and the heavy workload is nothing, but if you write it like this, your method will be exploding. So many methods can't be seen, don't mention how to use it.

At this time, you have to ask your leader for help and explain your confusion to him. I saw your leader think for a moment, and then confidently told you that using the combination mode not only can easily eliminate your confusion, but also achieve outstanding functionality.

He immediately showed you the encoding operation. First, he defined a statistics interface, which has two methods to be implemented:

public interface Statistics {int getBrowseCount();int getSalesCount();}

Then define a novelstatistics class used to count novel books and implement the two methods defined in the interface:

public class NovelStatistics implements Statistics {@Overridepublic int getBrowseCount() {int browseCount = 0;List<String> allNovels = getAllNovels();for (String novel : allNovels) {browseCount += getBrowseCount(novel);}return browseCount;}@Overridepublic int getSalesCount() {int saleCount = 0;List<String> allNovels = getAllNovels();for (String novel : allNovels) {saleCount += getSaleCount(novel);}return saleCount;}}

The two methods respectively calculate the page views and sales volume of novel books. In the same way, your leader defines a computerbookstatistics class to count the page views and sales volume of computer books:

public class ComputerBookStatistics implements Statistics {@Overridepublic int getBrowseCount() {int browseCount = 0;List<String> allComputerBooks = getAllComputerBooks();for (String computerBook : allComputerBooks) {browseCount += getBrowseCount(computerBook);}return browseCount;}@Overridepublic int getSalesCount() {int saleCount = 0;List<String> allComputerBooks = getAllComputerBooks();for (String computerBook : allComputerBooks) {saleCount += getSaleCount(computerBook);}return saleCount;}}

In this way, the specific statistical implementation will be dispersed in various classes, and there will be no more explosion in the method you just created. However, you have not started to use the combination mode yet, And your leader boasted that a good show is still coming soon.

Define another medicine bookstatistics class to implement the statistics interface, used to count the browsing volume and sales volume of medical books, the Code is as follows:

public class MedicalBookStatistics implements Statistics {@Overridepublic int getBrowseCount() {int browseCount = 0;List<String> allMedicalBooks = getAllMedicalBooks();for (String medicalBook : allMedicalBooks) {browseCount += getBrowseCount(medicalBook);}return browseCount;}@Overridepublic int getSalesCount() {int saleCount = 0;List<String> allMedicalBooks = getAllMedicalBooks();for (String medicalBook : allMedicalBooks) {saleCount += getSaleCount(medicalBook);}return saleCount;}}

I don't know if you have found out. Computer books and medical books are actually scientific books. They can be combined. At this time, your leader defines a technicalstatistics class for statistics on the combination of science and technology books:

public class TechnicalStatistics implements Statistics {private List<Statistics> statistics = new ArrayList<Statistics>();public TechnicalStatistics() {statistics.add(new ComputerBookStatistics());statistics.add(new MedicalBookStatistics());}@Overridepublic int getBrowseCount() {int browseCount = 0;for (Statistics s : statistics) {browseCount += s.getBrowseCount();}return browseCount;}@Overridepublic int getSalesCount() {int saleCount = 0;for (Statistics s : statistics) {saleCount += s.getBrowseCount();}return saleCount;}}

As you can see, because this class is a combination class, it is quite different from the previous classes. First, technicalstatistics has a constructor. In the constructor, computer books and medical books are added to the statistics list as subcategories, and then all subcategories are traversed in the getbrowsecount and getsalescount methods respectively, calculate their respective page views and sales volume, and then sum them to get the total value.

The combination mode has excellent scalability. There are no rules or rules, and you can combine them as you want. For example, all books are composed of different categories, your leader immediately showed off how to count the page views and sales volume of all books.

Defines an allstatistics class to implement the statistics interface. The specific code is as follows:

public class AllStatistics implements Statistics {private List<Statistics> statistics = new ArrayList<Statistics>();public AllStatistics() {statistics.add(new NovelStatistics());statistics.add(new TechnicalStatistics());}@Overridepublic int getBrowseCount() {int browseCount = 0;for (Statistics s : statistics) {browseCount += s.getBrowseCount();}return browseCount;}@Overridepublic int getSalesCount() {int saleCount = 0;for (Statistics s : statistics) {saleCount += s.getBrowseCount();}return saleCount;}}

In the allstatistics constructor, novels and scientific books are added to the statistics list as subcategories. Currently, you have only written these categories. Use the same method to calculate the page views and sales volume of all books in the getbrowsecount and getsalescount methods.

The current combination structure is as follows:

Now you can easily get the page views and sales of any classified books. For example, to get the page views of Science and Technology Books, you only need to call:

new TechnicalStatistics().getBrowseCount();

To obtain the total sales volume of all books, you only need to call:

new AllStatistics().getSalesCount();

Of course, you can also randomly change the combination structure, add books of various seed categories, and the hierarchy of sub-categories can be any deeper. As mentioned above, the combination mode is highly scalable.

Your leader tells you that the Code he has written has a high degree of repetition. In fact, you can optimize it and remove redundant code. Of course, this task will be handed over to you. Your leader is a busy man and has been running away for a long time.

Combination: Combine objects into a tree structure to represent the "part-whole" hierarchy. The combination mode ensures consistency between the use of a single object and a composite object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.