Design mode (iii): Adorner mode

Source: Internet
Author: User

I. Overview

  The Adorner mode dynamically attaches responsibility to the object. To extend functionality, decorators provide an alternative to inheritance. A simple description is a wrapper object that gives the object new behavior.

Second, solve the problem

When a class wants to get a behavior, we think of the inheritance of one of the four object-oriented features, which allows subclasses to derive behavior from the parent class for good code reuse. But this inherited behavior is statically determined at compile time, and all subclasses inherit the same behavior. If we want to extend the behavior of an object, we need to create a subclass to modify the parent class's methods (that is, to override the parent class behavior), creating a subclass for each extension of the behavior, which can cause a lot of problems. First, if there are many behaviors that need to be extended, the subclass will create countless multiple (causing the class to explode). Second, if the behavior in a subclass relies on a member variable, the code of the subclass is modified (Code maintenance Nightmare)when the member variable changes.

For example, the Getcost () method to obtain the price of tea, each new listing of a tea drink to create a subclass; When the price of some of the tea ingredients changes, we need to modify the subclass code.

Decorator mode is the solution to the above problem, it uses the combination of practices to extend the object behavior, can be dynamically extended at run time, write new code to add new functionality, without modifying existing code.

Third, structure class diagram

Iv. Role of Members

1. Abstract component (Component) Role: defines a class that will receive additional responsibilities, that is, the class that inherits the abstract class has the ability to decorate and be decorated.

  2. Specific component (concretecomponent) role : A class that can be dynamically added to a new behavior, decorated by decorators.

  3. Decorator (Decorator) role: Decorator abstract class, inheriting the ability of the class to have decorators.

  4. Specific decorator (concretedecorator) Role: Add new behavior for specific components.

V. Examples of applications

Below we use milk tea Beverage price example to analyze the use of the decorator, buy milk tea when we can buy pure milk tea, can also add pearls, coffee and other ingredients, but the price certainly not the same

For the first time we created abstract components, namely tea drinks

Public abstract class Tea {string description = "Unknown tea";//Description Public String getdescription () {return description;} Return the price of tea public abstract double getcost ();}

 Then create the abstract ingredient, which is the decorator

Public abstract class Condimentdecorator extends tea{//all spices must be re-implemented to describe the method public abstract String getdescription ();}

Create milk tea, concrete components, inherit abstract components, decorated objects

public class Milktea extends Tea{public Milktea () {description = "milk tea";} @Overridepublic Double Getcost () {//return tea milk price return 3.0;}}

The creation of the pearl ingredient, is the concrete decorator, inherits the abstract ingredient, realizes the decoration to the milk tea

public class Pearl extends condimentdecorator{//holds a reference to the adorned object private tea tea;public Pearl (tea tea) {This.tea = Tea;} @Overridepublic String getdescription () {return "pearl," +  tea.getdescription ();} @Overridepublic Double Getcost () {//The price of the tea plus the price of the Pearl, get the final result return 1.0 + Tea.getcost ();}

Create coffee ingredients, is the specific decorator, inherit abstract ingredients, to achieve the decoration of milk tea

public class Coffee extends condimentdecorator{//holds a reference to the adorned object private tea tea;public Coffee (tea tea) {This.tea = Tea;} @Overridepublic String getdescription () {//Add coffee after the description return "coffee," + tea.getdescription ();} @Overridepublic Double Getcost () {//tea price plus coffee price, calculate the result return 2.0 + tea.getcost ();}}

Test decorator

public class Testdecorator {public static void main (string[] args) {//Create a cup of pure milk tea, do not need to add seasoning, print out the description and price tea tea = new Milktea ();  System.out.println (tea.getdescription () + "Price: ¥" + tea.getcost ());//Create a spicy tea with spices tea tea2 = new Milktea ();//Add a copy of the Pearl TEA2 = new Pearl (TEA2);//Add a copy of the pearl TEA2 = new Pearl (TEA2);//Add a coffee seasoning tea2 = new Coffee (TEA2);//print Spiced milk tea System.out.println ( Tea2.getdescription () + "Price: ¥" + tea2.getcost ());}

  Operation Result:

Decorator's use in Java I/O

Java I/O is the most typical example of using decorator mode, see the following InputStream class diagram

Vi. Advantages and Disadvantages

  1. Advantages

(1), the use of combinations and delegates to dynamically expand the behavior, without modifying the existing code.

(2), can be used to wrap an object with multiple decorators, get different object combinations, so that the function of the packaged class more powerful.

(3), decorators and decorated people have the same super-class, in the need to be decorated in the occasion, can be decorated with objects to replace the original decorator.

(4), decorators and decorators are independent of each other, we can add and change specific components and specific decorators as needed, and finally use them in combination to conform to the "open and closed principle".

(5), to avoid the extension of the object by inheriting the function of the poor flexibility, sub-class infinite expansion of the problem (class explosion).

2. Disadvantages

(1), resulting in the design of many small objects, if overused, will make the program complicated.

(2), too many decorative chain will make the program inefficient, but also increased the difficulty of use and troubleshooting.

Vii. use of the scene

 1, when the need to dynamically expand the behavior of the object, or to dynamically increase the functionality of the use.

2, when the use of inheritance to the system function extension is limited, or inheritance is not conducive to system expansion and maintenance.

Viii. Summary

1, decorators and decorated objects have the same super-type.

2, you can use one or more decorators to wrap an object.

3, can at any time, the use of different decorator combination to decorate the object.

4, the decorator may in the adornment person's behavior front, the back adds own behavior, even replaces the adornment person's behavior, achieves the specific goal.

Design mode (iii): Adorner mode

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.