Java design pattern-decorator decorator mode

Source: Internet
Author: User

One, decorator mode

1. Definition and role

This mode extends the functionality of the object in a transparent manner to the client.

2. Role-related
Abstract component role: Defines an abstract interface to standardize the classes that prepare additional functionality.

Concrete Component role: the class that will be attached to the function, implementing the abstract component role interface.

Abstract Decorator Role: holds a reference to a specific component role and defines an interface that is consistent with the abstract component role.

Specific decorative roles: implements the abstract decorator role, which is responsible for adding additional functionality to specific artifacts.


3. Simple implementation
Abstract component role Java code:

Package com.pattern.decorator2;/** * Abstract Widget Role * @author ZDW * */public interface component{    //default method a    void Functiona ( );}

  



Specific component roles:
Package com.pattern.decorator2;/** * Concrete Component Role * @author ZDW * */public class Concreatecomponent implements component{        PU Blic void Functiona ()    {        System.out.println ("Function A");}    }

  



Abstract Decorator Role:
Package com.pattern.decorator2;/** * Abstract Decorator Role *  * @author ZDW *  */public class Decorator implements component{
   
    //Abstract Component Role Reference    private Component Component;        Public Decorator (Component Component)    {        this.component = Component;    }    public void Functiona ()    {        Component.functiona ();    }}
   

  


Specific decorator role 1:
Package com.pattern.decorator2;/** * Specific decorator role * @author ZDW * */public class ConcreateDecorator1 extends decorator{    PU Blic ConcreateDecorator1 (Component Component)    {        super (Component);    }    @Override public    void Functiona ()    {        Super.functiona ();        This.functionb ();    }    Expand    private void Functionb ()    {        System.out.println ("function B") according to your own needs;}    }

  



Specific Decorator role 2:
Package Com.pattern.decorator2;public class Concreatedecorator extends decorator{public    concreatedecorator ( Component Component)    {        super (Component);    }    @Override public    void Functiona ()    {        Super.functiona ();        This.functionc ();    }    private void Functionc ()    {        System.out.println ("Fucntion C");}    }

  



Test class:
Package com.pattern.decorator2;/** * Test Client *  * @author ZDW *  */public class client{    /**     * @param args
   
    */public    static void Main (string[] args)    {        //a layer of layers for method combination        Component Component = new Concreatedecorator (New ConcreateDecorator1 (                new Concreatecomponent ()));        Component.functiona ();    }}
   

  


OO principle: Dynamically attaches responsibility to an object. To extend functionality, decorators provide an alternative to inheritance.

Points:
1. Inheritance is one of the extension forms, but it is not necessarily the best solution to achieve elastic design.
2. In our design, the behavior should be allowed to be extended without having to modify the existing code.
3. Combinations and delegates can be used to dynamically add new behavior at run time.
4, in addition to inheritance, decorator mode also allows us to expand the behavior.
5. Decorator mode means a group of decorator classes, which are used to package specific components.
6. The Decorator class reflects the type of component being decorated (in fact, they have the same type, all through an interface or an inheritance implementation).
7, the decorator can be in front of the behavior of the decorator and/or after adding their own behavior, or even be the adornment of the entire act to replace the behavior, and achieve a specific purpose.
8, you can have no number of decorators packaging a component.
9, the decorator is generally transparent to the customer, unless the client program depends on the specific type of the component.
10, the decorator will lead to a lot of small objects in the design, if overused, will make the program become very complex.

Second, from the java.io package to see the decorative mode

Transferred from: http://tanshenghui.javaeye.com/blog/618724

===================================

It can be discussed from the class level of Io, the design pattern of IO framework.

Overall, IO can be divided into byte stream and character stream, the difference is that the character stream is wrapped by the byte stream, after Io is read into the JVM processing, the byte stream into character streams. What character encoding is used for characters in a character stream is determined by the JVM's default encoding.
And each stream is divided into input and output, so, overall, IO has four top-level classes:
InputStream
OutputStream
Reader
Writer

The machine-level interaction with the machine is a byte stream:
InputStream
OutputStream

In the middle class of Io, a transition of byte stream to a character stream, usually as a construction parameter of a character stream class, can be specified by encoding:
InputStreamReader
OutputStreamWriter

The buffer container of the byte stream and the character stream, in terms of bytes and char, is derived from:
Bytearrayinputstream
Bytearrayoutputstream
Chararrayinputstream
Chararrayoutputstream

The above class simply represents the representation of the stream, and in the form of transmission It also shows whether there is buffering. Therefore, the subclass can be derived as a buffered class:
Bufferinputstream
Bufferoutputstream
Bufferreader
Bufferwriter

Each top-level class has support for directory files (file):
FileInputStream
FileOutputStream
FileReader
FileWriter

In Java, a powerful feature is the ability to serialize objects into binary output, which is a byte stream output instead of a character stream output, so there are top-level InputStream and OutputStream derived classes:
ObjectInputStream
ObjectOutputStream

The flow includes the node stream and the filter stream, and the filtering stream is used to manipulate the data while reading and writing, and the synchronization operation is realized, and the top-level filter Stream class:
FilterInputStream
Filteroutputstream
Its subclasses, on the basis of which the node flows are encapsulated, the common subclasses are:
Bufferinputstream Bufferoutputstream
DataInputStream DataOutputStream
Linenumberinputstream PrintStream
You can refer to the construction methods of subclasses.

The above IO operation is almost the loading of the stream into memory, the operation of which is sequential read and write, and the need for random read and write:
Randomaccessfile

From the interface of the structure implementation of the whole class framework, the top-level class:
InputStream implements Closable,
OutputStream implements Closable, flushable
Reader implements Closable, readable
Writer implements Closable, Flushable, appendable
Each interface method:
Closable:close ();
Flushable:flush ();
Readable:read (Charbuffer CB);
Appendable:append ();
From the rules of the IO class, it is natural and necessary to implement these methods. such as: The stream must be closed before the flow output must be refreshed.

Note that none of the four top-level classes implement the Serializable interface.
Although Java.io.Serializable is an IO framework, it does not directly act on the IO Framework's four top-level IO classes and their subclasses, but instead works on other objects so that they can be serialized and input and output through the IO class. such as: File, ObjectStreamClass, String.

There are two design patterns in the Java IO framework: Decorative mode and adapter mode.

Just leave Java io is divided into two parts of elements and behaviors, and the elements are adapted, while the behavior is decorated with reinforcement.

The adapter pattern mainly lies in the conversion of byte streams to character stream and the wrapper of elements, such as class: InputStreamReader, CharArrayReader, FileReader, Pipedreader, StringReader.
Decoration mode is mainly in the intensification of convection, such as buffering, filtering, row positioning, such as class: BufferedReader, FilterReader, LineNumberReader.

A typical example of this is:
Bufferreader br = new Bufferreader (new InputStreamReader (system.in));
Combined two modes: the InputStream to fit into the InputStreamReader, and then the inputstreamreader to strengthen the decorative city BufferedReader.

Java design pattern-decorator decorator mode

Related Article

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.