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