Design Pattern Learning: Decorator mode

Source: Internet
Author: User

Decorator (decorator) mode is also called packaging mode, the combination of the way to expand the function of the object is an alternative to the inheritance relationship.

Definition Description : The decorator pattern dynamically attaches responsibility to an object, and to extend functionality, decoration provides a more flexible alternative than inheritance.

experience from the example :

Examples from the Headfirst book (recommended to read the book, the example is too good), is the Starbucks example. Starbucks Coffee is very famous (poor students, now can't afford O (╯-╰) o). They supply many kinds of coffee. At first their class design was the following.

But because of the purchase of coffee, will add heavier spices, such as: Steamed milk (steamed Milk), soy milk (Soy), Mocha (Mocha, that is, chocolate flavor), or cover the milk bubble. Starbucks will charge a different fee for various spices. So the order system must consider these. Think about, at first we encountered this problem will do, so that each special coffee beans + seasoning into a class, it seems to solve the problem, but, if the seasoning a lot, the type of coffee beans a lot of words, the total number of classes = coffee beans type * Seasoning quantity. Actually very many kinds of. This is not going to work.

What then, in beverage itself? Designed to be like the following structure?

Learn the opening and closing principles (forget to see here), we understand that this practice of breaking the principle of opening and closing, but also a little, remember the principle of combination of reuse? Use a combination rather than an inheritance, where you should prioritize the combination.

Use the decorator pattern here to solve it. It is like this, first of all, we choose the type of coffee beans, here choose the kind of 1

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.