Java IO Decorator Mode

Source: Internet
Author: User
Tags wrapper

Decorative Mode (Decorator)

Decorative mode is also known as Packaging (Wrapper) mode .

Adornment mode extends the functionality of the object transparently to the client, and is an alternative to the inheritance relationship .

The decorating mode wraps the real object by creating a wrapper object, which is the decoration.

Decorating mode Dynamically attaches more responsibility to an object in a way that is transparent to the client. In other words, the client does not feel that the object is different before and after decorating.

Adornment mode expands the functionality of an object without creating more subclasses.

The adornment mode delegates the client's call to the decorated class. The key to decorating mode is that this extension is completely transparent.

the role of decoration mode

  Abstract Component Role (Component): An abstract interface is given to standardize the objects that are ready to receive additional responsibilities.

  Concrete Component Role (concrete Component): defines the class that will receive additional responsibilities.

  Decorative Role (Decorator): holds a reference to a component (Component) object and defines an interface that is consistent with the abstract component interface.

  The specific decorative role (concrete Decorator): responsible for the component object "affixed" additional responsibility.

decorative Patterns in Java io

In Io, the specific component role is the node flow , and the decorative role is the filter stream .

FilterInputStream and Filteroutputstream are decorative roles, while others that derive from them are specific decorative roles.

features of decoration mode

Decorative objects and real objects have the same interface. This allows the client object to interact with the adornment object in the same way as the real object.

The Adornment object contains a reference to a real object (reference).

The adornment object receives all requests from the client, which forwards the requests to the real object.

Decorative objects can attach some functionality before or after forwarding these requests.

This ensures that additional functionality can be added externally without modifying the structure of a given object at run time.

Program Examplespublic Interface component{
Public void dosomething ();
}

This is an abstract component role and is an interface. The specific component role implements this interface:

Public class Concretecomponent implements component{
@Override
public void dosomething () {
System.out.println ("function A");
}
}

Decorative characters:

PublicClass DecoratorImplementscomponent{
PrivateComponent Component;
PublicDecorator (Component Component) {
This.component =Component
}
@Override
Public void DoSomething () {
Component.dosomething ();
}
}It contains a reference to a component role, and a method that takes advantage of a component role in a method invocation.

Specific decorative characters (two):

PublicClass ConcreteDecorator1Extendsdecorator{
PublicConcreteDecorator1 (Component Component) {
Super(component);
}
@Override
PublicvoidDoSomething () {
Super. dosomething ();
This. doanotherthing ();
}
private void doanotherthing () {
System.out.println ("function B");
}
} PublicClass ConcreteDecorator2Extendsdecorator{
PublicConcreteDecorator2 (Component Component) {
Super(component);
}
@Override
PublicvoidDoSomething () {
Super. dosomething ();
this. doanotherthing ();
}
private void doanotherthing () {
System.out.println ("function C");
}
}To use the test:

PublicClassclient{
PublicStaticvoidMain (string[] args) {
Component Component =NewConcretecomponent ();
Component Component1 =New ConcreteDecorator1 (component);
Component1.dosomething ();
System.out.println ("-----------");
Component Component2 = new ConcreteDecorator2 (Component1);
Component2.dosomething ();
}
}

Problem Introduction

Coffee Shop Class Design:

A beverage base class, a variety of beverage classes inherit this base class and calculate their price.

To add a variety of spices in the beverage, consider adding some Boolean variables to the base class to indicate whether to add a variety of spices, the cost of the base class () to calculate the price of the various spices, the sub-category cover costs (), and in which the cost of the Super-class (), plus the price of a particular beverage, to calculate the price

Disadvantages: The number of classes explosion, the new function of the base class addition does not apply to all subclasses, seasoning price changes, the emergence of new spices will require changes to existing code, and some sub-categories are not suitable for certain spices and other situations ...

Design Principles

  Classes should be open to extensions and closed for modifications.

Our goal is to allow classes to be easily extended and to match new behavior without modifying existing code.

What are the benefits of achieving such a goal? This design is resilient to change and can accept new features to respond to changing needs.

It is not easy to have an OO design that is both open and closed, and it is generally not necessary to design every part of the design.

Following the open-close principle, it is common to introduce new levels of abstraction and increase the complexity of the code.

We need to focus on where the design is most likely to change, and then apply the open-close principle.

use decorator mode to solve problems

Ways to solve a coffee shop drink problem:

Take the beverage as the main body, then "decorate" the beverage with seasoning at run time.

For example, customers want Mocha (Mocha) and milk foam (Whip) deep-roasted coffee (darkroast):

Darkroast inherits from Beverage and has a cost () method.

The first step is to start with the Darkroast object;

In the second step, the customer wants Mocha, so create a Mocha decorator object and use it to wrap the Darkroast object (wrap) up;

In the third step, the customer wants the milk bubble, so build a whip object and use it to wrap the Mocha object, (Mocha and whip also inherit from beverage, there is a cost () method);

Finally, for the customer to calculate money, by calling the most outer ring decorator (Whip) cost () can be. The cost of Whip () will first be entrusted to the object it decorates (Mocha) to calculate the price, and then add the price of the milk bubble. Mocha's cost () is similar.

features of decorator mode

Decorators and decorated objects have the same super-type .

You can wrap an object with one or more adorners.

Because the decorator and the decorator have the same type, any occasion where the original object is needed can be replaced with a decorated object.

  The decorator may, before and/or after the act entrusted to the decorator, add his or her own behavior to achieve a specific purpose.

Objects can be decorated at any time, so you can decorate objects dynamically and without limits at run time with your favorite decorators.

the definition of decorator mode

The decorator mode dynamically attaches responsibility to the object. To extend functionality, decorators provide a more resilient alternative than inheritance.

the implementation of decorator mode

The implementation class diagram is as follows:

Decorators and decorators have a common superclass, using inheritance to achieve " type matching ", rather than using inheritance to obtain "behavior"; combine decorators and decorators to add new behavior.

To solve the specific problem of the beverage in this article, the figure component is beverage (can be abstract class or interface), and concretecomponent for a variety of drinks, Decorator (abstract decorator) as a condiment abstract class or interface, Concretedecoratorx is a variety of specific spices.

Because of the combination of objects, it is possible to mix and match the beverage and seasoning more flexibly.

Code External details:

When implemented in code, the decorator can be passed into the decorator by the constructor, as in the final invocation form as follows:

Beverage beverage = new Darkroast ();

Beverage = new Mocha (beverage);

Beverage = new Whip (beverage);

The two-tier wrapper is completed, and the cost () function of the beverage is then called to get the total price.

decorator mode in the Java.io package

The disadvantage of decorator mode: Adding a large number of small classes in the design, if overused, can complicate the program.




Java IO Decorator 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.