I think any book about the mode can't help but mention its practical application when talking about the decorator mode-applications in the Java/IO library, <Java and mode> This book is no exception, but it is a bit different. This book has a special topic during introduction. It looks at the Java/IO library in two modes, after completing this topic, I personally feel that I have a new understanding of the Java/IO library, while also deepening the understanding of the decorator mode and adapter mode, I would like to share with you the great achievements I have made. At the same time, I would like to explain that most of the following texts and images come from <Java and mode>. I. Introduction (Java I/O in general) regardless of the programming language, input and output are an important part, and Java is no exception, in addition, Java greatly expands the input/output functions and application scope. It uses the stream mechanism to implement input/output. The so-called stream is the orderly arrangement of data, and the stream can be from a source (called streams or source of stream, to a destination (called a streaming or sink of stream. A program reads data from the input stream and writes data to the output stream. 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, just like a Stream pipeline, inhale a certain type of data from a shard and output some type of data. The above is called a Stream pipeline diagram. Similarly, you can use the fileoutputstream class to write data to a disk file, as shown in. This mechanism is not very useful in actual application, and the program needs to write very structured information, therefore, the byte data is actually numeric, text, source code, and so on. The Java I/O Library provides a chaining mechanism that connects a stream processor to the beginning and end of another stream processor and uses the output of one of them as the input, form a Stream pipeline link. For example, the datainputstream stream processor can use the output of the fileinputstream Stream object as the input, and convert the byte type data to the original Java type and string type data. As shown in: Similarly, writing byte 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 during writing. The dataoutputstream stream processor receives the raw data type and the string data type, while the output data of this stream processor is of the byte type. That is to say, dataoutputstream can convert the source data to byte data and then input it. In this way, you can link dataoutputstream to fileoutputstream, so that the program can write source data of the original data type and string type into the dual pipeline of this link, to write structured data to a disk file, as shown in: this is the role of the link. Stream processors must process streams. If you classify the streams processed by stream classes, they can be divided into two categories: the first array, string, and file, this is called the original token. Second, a stream of the same type is used as a link stream class, called a link pipeline. 2. Java I/O Library Design Principles the Java I/O Library abstracts a variety of common pipelines, streaming, and processing processes. The client's Java program does not need to know the final scheme, whether the streaming is a file on the disk or an array, or whether the data is buffered, and whether the data can be read by row number or other processing details. As mentioned in the book, people who first met the Java/IO library are all confused by the complexity of the library, and those who are familiar with the library, however, it is often difficult to argue whether the library is designed properly. The author of the book puts forward his own opinions. To understand the huge and complex library of Java I/O, the key is to master two symmetry and two design pattern modes. Java I/O libraries have two symmetry types: 1. Input-Output symmetry. For example, inputstream and outputstream occupy the root of two parallel hierarchical structures of input and output of byte streams. Reader and writer occupy the root of the two parallel hierarchical structures of the input and output of the char stream. 2 byte-Char symmetry. inputstream and reader sub-classes are responsible for the input of byte and char streams respectively. outputstream and writer sub-classes are responsible for the output of byte and char streams respectively, they form a parallel hierarchical structure. Two design modes of Java I/O Library: the overall design of Java I/O Library conforms to the decorator and adapter modes. As mentioned above, the class for processing a stream in this database is called a stream class. The fileinputstream, fileoutputstream, datainputstream, and dataoutputstream mentioned in the Introduction are examples of stream processors. 1. modifier mode: in the hierarchical structure represented by inputstream, outputstream, reader, and writer, some stream processors can play a decorative role on other stream processors to form a new one, stream processor with improved features. The modifier mode is the overall design mode of the Java I/O library. This principle complies with the decorator mode, as shown in: 2 adapter mode: Inside the hierarchical structure represented by inputstream, outputstream, reader, and writer, some stream processors adapt to other types of processors. This is the application of the adapter mode, as shown in. The adapter mode is applied to the original stream processor design and forms the starting point of all stream processors in the I/O library. JDK provides a large number of class libraries for programmers. To maintain the reusability, scalability, and flexibility of class libraries, a large number of design modes are used, this article describes the decorator mode used in the jdk I/O package, and uses this mode to implement a new output stream class. Decorator mode description decorator mode, also known as wrapper, is used to dynamically add some additional responsibilities to an object. It is more flexible than generating child classes. Sometimes, we need to add some new functions for an object instead of the entire class. For example, we need to add a scroll bar to a worker area. We can use the inheritance mechanism to implement this function, but this method is not flexible enough. We cannot control the method and timing of adding a scroll bar in the render area. In addition, when you need to add more functions to the partition, such as borders, you need to create a new class. When you need to combine these functions, it will undoubtedly cause the class explosion. We can use a more flexible method, that is, to embed the partition area into the scroll bar. The class of this scroll bar is equivalent to a decoration of the worker area. This decoration (scroll bar) must be inherited from the same interface as the decorated component, so that users do not have to care about the decoration implementation, because it is transparent to them. The decoration will forward user requests to corresponding components (that is, call related methods), and may make some additional actions (such as adding a scroll bar) before and after the forwarding ). In this way, we can add any number of functions by embedding different decorations in the embedding area according to the combination. This dynamic method of adding functions to objects does not cause class explosion, but also has more flexibility. The above method is the decorator mode, which dynamically adds new functions by adding decoration to the object. The following is a UML diagram of the decorator mode: component is a common parent class for components and decoration. It defines the methods required for subclass implementation. Concretecomponent is a specific component class. You can add decoration to it to add new functions. Decorator is a common parent class for all decorations. It defines the methods that must be implemented for all decorations. It also saves a reference to component to forward user requests to component, some additional actions may be executed before and after the request is forwarded. Concretedecoratora and concretedecoratorb are specific decorations that can be used to decorate specific component. java provided by JDK In the decorator mode in the Java Io package. the IO package uses the decorator mode to encapsulate various input and output streams. The following uses Java. Io. outputstream and its subclass as an example to describe how to use the decorator mode in Io. First, let's look at a piece of code used to create an IO stream: The following is a code snippet: Try {outputstream out = new dataoutputstream (New fileoutputstream ("test.txt");} catch (filenotfoundexception E) {e. printstacktrace ();} This code is no longer familiar to anyone who has used JAVA input/output streams. We use dataoutputstream to encapsulate a fileoutputstream. this is a typical decorator mode. fileoutputstream is equivalent to component, and dataoutputstream is a decorator. change the Code as follows to make it easier to understand: The following is a code snippet: Try {outputstream out = new fileoutputstream ("test.txt "); Out = new dataoutputstream (out);} catch (filenotfoundexception e) {e. printstatcktrace ();} since fileoutputstream and dataoutputstream have public parent class outputstream, object decoration is almost transparent to users. Next let's take a look at how outputstream and its subclass form the decorator mode: outputstream is an abstract class, which is the public parent class of all output streams. Its source code is as follows: public abstract class outputstream implements closeable, flushable {public abstract void write (int B) throws ioexception ;......} It defines the abstract method of write (int B. This is equivalent to the component class in decorator mode. Classes, fileoutputstream and pipedoutputstream are inherited directly from outputstream. Taking bytearrayoutputstream as an example: the following code snippet: public class bytearrayoutputstream extends outputstream {protected byte Buf []; protected int count; public bytearrayoutputstream () {This (32);} public bytearrayoutputstream (INT size) {If (size <0) {Throw new illegalargumentexception ("negative initial size:" + size );} buf = new Byte [size];} public synchronized void write (int B) {int newcount = count + 1; if (newcount> Buf. length) {byte newbuf [] = new byte [math. max (BUF. length <1, newcount)]; system. arraycopy (BUF, 0, newbuf, 0, count); Buf = newbuf;} Buf [count] = (byte) B; Count = newcount ;}......} It implements the write (int B) method in outputstream, so we can create the output stream object and complete the output in a specific format. It is equivalent to the concretecomponent class in decorator mode. Next, let's take a look at filteroutputstream. The Code is as follows: public class filteroutputstream extends outputstream {protected outputstream out; Public filteroutputstream (outputstream out) {This. out = out;} public void write (int B) throws ioexception {out. write (B );}......} It also inherits from outputstream. However, its constructor is very special. It needs to pass an outputstream reference to it and it will save the reference to this object. If no specific outputstream object exists, we cannot create filteroutputstream. because out can be a reference to the filteroutputstream type or a reference to a specific output stream class such as bytearrayoutputstream, we can add a variety of decorations for bytearrayoutputstream using multi-layer nesting. This filteroutputstream class is equivalent to the decorator class in the decorator mode. Its write (int
B) The method simply calls the write (int B) method of the incoming stream, but does not do more processing. Therefore, it essentially does not have streaming decoration, therefore, the subclass that inherits it must overwrite this method to achieve the purpose of decoration. Bufferedoutputstream and dataoutputstream are two subclasses of filteroutputstream. They are equivalent to concretedecorator in decorator mode, and different decorations are made on the input output stream. Take the bufferedoutputstream class as an example: the following code snippet: public class bufferedoutputstream extends filteroutputstream {...... Private void flushbuffer () throws ioexception {If (count> 0) {out. write (BUF, 0, count); Count = 0 ;}} public synchronized void write (int B) throws ioexception {If (count> = Buf. length) {flushbuffer ();} Buf [count ++] = (byte) B ;}......} This class provides a caching mechanism to write data into the output stream when the cache capacity reaches a certain byte. First, it inherits filteroutputstream and overwrites the write (int B) method of the parent class. before calling the output stream to write data, it will check whether the cache is full. If it is not full, it will not be written. In this way, new functions are dynamically added to the output stream object. Next, we will use the decorator mode to write a new output stream for Io. Write a new output stream by yourself. After understanding the structure of outputstream and its sub-classes, we can write a new output stream to add new functions. This section provides an example of a new output stream, which filters out space characters in the statements to be output. For example, to output "Java Io outputstream", the filtered output is "javaiooutputstream ". the following code is the skipspaceoutputstream class: The following is a code snippet: Import Java. io. filteroutputstream; import Java. io. ioexception; import Java. io. outputstream;/*** a new output stream, which will check the space character * and won't write it to the output stream. * @ author magic **/public class skipspaceoutputstream extends filteroutputstream {public skipspaceoutp Utstream (outputstream out) {super (out);}/*** rewrite the method in the parent class, and * skip the space character. */Public void write (int B) throws ioexception {If (B! = '') {Super. Write (B );
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