Java_ Design Pattern _ Decorator Mode _decorator pattern (2016-07-28)

Source: Internet
Author: User
Tags repetition

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.

structure of the decoration mode

  Decorating mode dynamically attaches more responsibility to an object in a transparent manner to the customer. 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 using the creation of more subclasses.

The class diagram for the decorating mode is as follows:

  

The roles in the decorating mode are:

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

Concrete Component (concretecomponent) Role: defines a class that will receive additional responsibilities.

decoration (Decorator) Role: holds an instance of a component (Component) object and defines an interface that is consistent with the abstract component interface.

specific decoration (concreteDecorator) Role: responsible for attaching the Component object "affixed" to the responsibility.

Source

Abstract component Roles

 Public Interface Component {        publicvoid  sampleoperation ();    }

Specific component roles

 Public class Implements Component {    @Override    publicvoid  sampleoperation () {         // write the relevant business code     }}

Decorative characters  

  

 Public class Implements component{    private  Component Component;          Public Decorator (Component Component) {        this. Component= Component;    }    @Override    publicvoid  sampleoperation () {        //  Delegate to component         component.sampleoperation ();    }    }

Specific decorative characters

 Public class extends Decorator {    public  Concretedecoratora (Component Component) {        super  (component);    }        @Override    publicvoid  sampleoperation () {  super. Sampleoperation ();         // write the relevant business code     }}

 Public class extends Decorator {    public  concretedecoratorb (Component Component) {        super  (component);    }        @Override    publicvoid  sampleoperation () {   super. Sampleoperation ();         // write the relevant business code     }}

application of design patterns in the Java I/O library

The most famous application of decorating patterns in the Java language is the design of the Java I/O standard library.

Because the Java I/O library requires a variety of combinations of performance, if these performance are implemented in an inherited way, then each combination requires a class, which results in a large number of performance-repeating classes appearing. In the case of decorative patterns, the number of classes is greatly reduced, and the repetition of performance can be minimized. Therefore, the decoration mode is the basic mode of the Java I/O library.

I. Overview of Java I/O

The Java input/output function uses the flow mechanism, the so-called flow, is the orderly arrangement of data, and the stream can be from a source (called a stream source or source of stream) out to a destination (called a stream or sink of stream) to go. By the direction of the stream, it can be divided into the input stream and the output stream, a program reads data from the input stream to the output stream to write data.

For example, a program can use the FileInputStream class to read data from a disk file, as shown in:


  

A processor like FileInputStream is called a stream processor, which, like a stream pipeline, sucks in some type of data from a stream source and outputs some kind of data. Above this is called the flow of pipe diagram.

Similarly, you can use the FileOutputStream class to write data to a disk file, as shown in:

  

In practice this mechanism is not not very useful, the program needs to write often very structured information, so these byte types of data is actually some numeric values, text, source code and so on. The Java I/O library provides a mechanism for calling a link (Chaining) to connect one stream processor to another, with one of the outputs as input, forming a link to a flow pipeline.

For example, the DataInputStream stream processor can take the output of the FileInputStream stream object as input, converting the data of type Byte to Java's original type and string type data. As shown in the following:

Similarly, writing a byte type of data to a file is not a simple process. The data that a program needs to write to a file is often structured, while the byte type is the original type. Therefore, it must be converted when it is written. The DataOutputStream stream processor provides the raw data type and the string data type, and the output data of the stream processor is byte type. This means that DataOutputStream can convert the source data into byte type data and then lose it.

In this way, you can link DataOutputStream with FileOutputStream so that the program can write the original data type and the string type of source data into the linked double pipeline, to the purpose of writing the structured data into the disk file, As shown in the following:

 

Stream processors must have a stream source for the stream they are processing, and if you classify the stream source that the stream class handles, it can be divided into two main categories:

The first array, string,file, etc., is called the primitive stream source.

The second stream of the same type is used as the stream source of the link stream class, called the link stream source.

Two. Design principles for the Java I/O Library

To understand the large and complex library of Java I/O, the key is to master two symmetries and two design pattern patterns:

The 1.Java I/O library has two symmetries:

① input-output symmetry, such as InputStream and OutputStream, each occupy the root of the two parallel hierarchical structure of the input and output of a byte stream. Both reader and writer occupy the root of the two parallel hierarchical structure of the input and output of the char stream.

②byte-char symmetric, InputStream and reader subclasses are responsible for the input of byte and char streams respectively, and the subclasses of OutputStream and writer are responsible for the output of byte and char streams respectively, which form parallel hierarchies.

Two design modes for the 2.Java I/O Library:

① decorator Mode (Decorator): Inside the hierarchy represented by Inputstream,outputstream,reader and writer, there are some stream processors that can decorate other stream processors to form new, improved functionality of the stream processor. Decorator mode is the overall design pattern for the Java I/O library.

② Adapter Mode (Adapter): Within the hierarchy represented by Inputstream,outputstream,reader and writer, there are some stream processors that are suitable for other types of flow sources, which is the application of the adapter pattern.

Three. Application of decoration mode

Why not inherit and use decorative mode

We know that the Java I/O library requires a variety of combinations of performance, and if these combinations of performance are implemented by inheritance, then each combination requires a class, which causes a large number of recurring problems to explode. In the case of decorative mode, not only the number of classes is greatly reduced, the performance of the repetition can be reduced to a minimum. So the decorating mode is the basic mode of the Java I/O library.

Here I would like to use an example of <

It's an example of this: beverage is an abstract class that is inherited by all the drinks sold in a coffee shop. Beverage has an abstract approach to cost, and all subclasses implement this abstract method to calculate their price. Now there are four basic coffees: Houseblend,darkroast,decaf,espresso They all inherit from beverage, and now the need is to say in four basic coffee, each can be casually add condiments, like steamed Milk,soy , and Mocha finally add whipped milk. If we are to implement the combination of these spices and the original coffee according to inheritance, we will naturally design the following class diagram:

  

See the above class diagram, we can not help but say that this is "class explosion." If it is according to the design idea of decorative mode we can draw the following design class diagram:

  

 The first is the decorative pattern in the InputStream type:

InputStream has seven direct specific subclasses, with four specific subclasses belonging to FilterInputStream, as shown in:

  

 

All of the classes are called stream processors, and this diagram is called a stream processor diagram (InputStream type).

These stream classes are divided into two types based on the type of source of the input stream, the original stream class (Original stream) and the link stream processor (Wrapper stream).

  Raw Stream Processor

The original stream processor receives a byte array object, a String object, a Filediscriptor object, or a different type of stream source object, according to the diagram above, the original stream processor consists of the following four types:

Bytearrayinputstream: Provides a buffer operation function for multi-threaded communication, receiving a byte array as the source of the stream.

FileInputStream: Create a file-related input stream. Receives a file object as the source of the stream.

PipedInputStream: Can be used in conjunction with PipedOutputStream to read data from a data pipeline and receive a pipedoutputstream as a source.

StringBufferInputStream: Converts a string buffer to an input stream. Receives a string object as the source of the stream. (description on the JDK Help document: obsolete.) This class failed to correctly convert characters to bytes. Starting with JDK1.1, the preferred way to create a stream from a string is to create it through the StringReader class. Only the lower eight bits of each character in the string can be used by this class. )

  Link Stream Processors

 The so-called link stream processor is a class that can receive another stream object as its source and extend its functionality. InputStream types of link processors include the following, all of which receive another InputStream object as a stream source.

(1) FilterInputStream is called a filtered input stream, which takes another input stream as a stream source. Subclasses of this class include the following types:

Bufferedinputstream: Used to read data from the hard disk into a memory buffer and provide data from the buffer.

DataInputStream: Provides a multibyte-based read method that can read raw types of data.

Linenumberinputstream: Provides a filtered input stream with a row count function.

Pushbackinputstream: Provides special functionality to "push back" the bytes that have been read into the input stream.

(2) ObjectInputStream can re-parallelize raw data types and objects that use ObjectInputStream serialization.

(3) Seqcueneinputstream can connect two existing input streams to form an input stream, thus arranging multiple input streams to form an input stream sequence.

  Abstract structure diagram

  Following the partitioning of the original stream processor and the link stream processor above, it is possible to describe the relationship between them using the structure diagram below.

  

Decorative pattern structure diagram

  

FilterInputStream inherits InputStream and InputStream, and it has four subclasses, which is called the decorator pattern.

The above diagram conveys this message to us that the link stream object receives an original stream object or another link stream object as a stream source, and on the other hand their internal working methods of the convection source have been changed accordingly, and this change is the purpose of the decorative pattern. Like what:

Bufferedinputstream "decorates" the internal working mode of the InputStream, which makes the read-in operation of the stream use a buffering mechanism. After the buffering mechanism is used, a physical read action is not generated for every stream read operation, which improves the efficiency of the program and should be used in the process of reading the physical stream.

Linenumberinputstream and Pushbackinputstream also "decorate" the internal work of InputStream, the former allows the program to read into the data according to the line number, the latter can make the program read in the process, back a character.

The DataInputStream subclass reads the various raw data types and the string type of data, which can be seen from the various read methods it provides, such as: ReadByte (), ReadInt (), Readfloat (), and so on.

Decorative patterns in the other three types:

the I/O Library of the J Ava language provides four hierarchical structures: Inputstream,outputstream,reader,writer four series classes. InputStream and OutputStream handle 8-bit byte stream data, and reader and writer process 16-bit character stream data. InputStream and Reader process input, OutputStream and writer process the output, so outputstream,reader, Writer of these three types of decorative mode with the above details of the InputStream decoration mode is similar. To facilitate comparison of these types, incidentally, the Java language I/O hierarchy chart is attached:

The following diagram shows: Hierarchical relationships formed by InputStream and OutputStream

  

The following diagram shows the hierarchical relationship that is formed by reader and writer

  

Four. Application of Adapter mode

Don't write

Content Source Reference:

Http://www.cnblogs.com/java-my-life/archive/2012/04/20/2455726.html

http://blog.csdn.net/hijiankang/article/details/51027565

http://blog.csdn.net/ivokky/article/details/9175065

Java_ Design Pattern _ Decorator Mode _decorator pattern (2016-07-28)

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.