Study and explore the Java design pattern--The decorator mode __java

Source: Internet
Author: User
Tags stringbuffer
definition

Decorator Mode: Dynamically attaching responsibilities to objects without changing the original class file and not using inheritance, thereby enabling the ability to dynamically expand an object. It is by creating a wrapper object that is decorated to wrap the real object. Design Principles

To use the decorator pattern, the following design principles need to be met:
1, multiple use combination, less use of inheritance
2, open-close principle: Class should be open to expand, to modify the UML class diagram

Let's take a look at the class diagram of the decorator pattern, and then go into detail:

From the top down:
1, Component is the base class. Usually an abstract class or an interface that defines a property or method, and the implementation of the method can be implemented by subclasses or implemented by itself. This class is not typically used directly, but rather by inheriting the class to implement a specific function that constrains the behavior of the entire inheritance tree. For example, if the component represents people, even by decorating it will not make people into other animals.
2. Concretecomponent is a subclass of component, which implements the corresponding method, which acts as the "decorated person" role.
3. Decorator is also a subclass of component, which is an abstract class (or interface) that the decorator implements together. For example, decorator represents a kind of adornment such as clothing, then its subclass should be a T-shirt, skirt such as the specific decoration.
4, Concretedecorator is a decorator subclass, is a specific decorator, because it is also component subclass, so it can easily expand the component state (such as adding a new method). Each decorator should have an instance variable to hold a reference to a component, which also leverages the attributes of the combination. After holding the component reference, because of its own is also a component subclass, then, the equivalent of concretedecorator wrapped component, not only has the component characteristics, but also itself can be different characteristics, which is called decoration . A Sample

To understand the decorator pattern more profoundly, let's look at a simple chestnut. First, let's assume that there is a demand now: You have a clothing store that sells all kinds of clothes, and now you need to use a system to record the total price of the clothes the customer wants to buy for easy settlement. So in this example, we can use the decorator mode, the customer as being decorated, clothing is decorated, this is very intuitive image, then we step by step to achieve demand. Step 1, create component base class

Because the overall object is human, we can abstract people as base classes and create new Person.java:

public abstract class Person {
    String description = "Unkonwn";

    Public String getdescription ()
    {return
        description;
    }

    public abstract double (); Methods that subclasses should implement
}
Step 2, create the decorated person--concretecomponent

Customers are divided into many kinds, there are children, teenagers, adults and so on, so we can create different decorated people, here we create young people decorated, new Teenager.java:

Public class teenager extends person {public

    teenager () {
        description = "Shopping List:";
    }

    @Override public
    double () {
        //Nothing bought, no money return
        0;
    }

Step 3, create decorator

Since different parts have different clothing, can not be confused, for example, clothing, hats, shoes, etc., then here we create the decorator for clothes and hats, respectively new Clothingdecorator.java and Hatdecorator.java:

Public abstract class Clothingdecorator extends person {public

    abstract String getdescription ();
}
Public abstract class Hatdecorator extends person {public

    abstract String getdescription ();

}
Step 4, create Concretedecorator

Now that we've created two kinds of decorator, we expand them to create different decorators, for clothing, we create a new Shirt.java, for hat, we create a new Casquette, You can actually create more different decorators based on different types of clothing, and here are just two types of presentations. The code looks like this:

public class Shirt extends Clothingdecorator {

    ///Save person's reference person by instance variable
    ;

    Public shirt
    {
        This.person = person;
    }

    @Override public
    String getdescription () {return
        person.getdescription () + "a shirt  ";
    }

    The @Override public
    double () {return
        + person.cost ();///Implement the cost () method and call the person's value () method to obtain all cumulative values
    }

}
public class Casquette extends Hatdecorator {Person of person

    ;

    Public Casquette {
        This.person = person;
    }
    @Override public
    String getdescription () {return
        person.getdescription () + "a casquette  ";//Cap
    }

    @Override public
    double () {return
        + person.cost ();
    }

}

Finally, we test our code in the test class:

public class Shopping {public

    static void Main (string[] args) {person person
        = new teenager ();

        person = new shirt (person);
        person = new Casquette (person);

        System.out.println (person.getdescription () + "¥" +person.cost ());
    }

First create a teenager object, then decorate it with shirt, become dressed in shirt teenager, and then decorate with casquette, become wearing casquette wearing shirt teenager. The results of the run are as follows:

Let's comb through the logic above and draw a Wayne chart that looks like this:

Teenager, shirt, Casquette are inherited from the person base class, but the specific implementation of different, teenager is a direct subclass of persons, representing the decorated; teenager, shirt is the decorator, save the person's reference, Implementation of the cost () method, and in the cost () method, not only to achieve their own logic, but also called the person referred to the cost () method, that is, to obtain the information of the decorated people, this is a feature of the decorator, The purpose of saving a reference is to obtain the status information of the decorated person in order to combine their own attributes. features

Above is the decorator pattern of a small chestnut, tells the decoration of the basic usage. Through the above examples, we can sum up the characteristics of the decorator pattern.
(1) The adorner and the decorated person have the same interface (or have the same parent class).
(2) The decorator holds a reference to a decorated person.
(3) The adorner accepts all client requests, and these requests are eventually returned to the decorated person (see Wayne Chart).
(4) Dynamically adding properties to an object at run time without changing the structure of the object.

The greatest advantage of using the decorator pattern is that it is very well developed, and the flexibility is better than direct inheritance by using different decorative classes to make objects have a variety of attributes. However, it also has drawbacks, that is, there will be many small categories, that is, decorative classes, so that the program becomes complex. Application

After learning the usage, characteristics and advantages and disadvantages of the decorator pattern, we will take a look at the application of the decorator pattern in the actual development process. The place where decorator patterns often appear in Java is Javaio. When it comes to Javaio, there are a lot of classes in mind: InputStream, FileInputStream, Bufferedinputstream ... And so on, really big head, in fact, most of these are decorative class, as long as it is easy to understand this point. Let's look at how Javaio uses the decorator pattern.
From the character stream analysis, we know that there are two base classes, respectively, InputStream and OutputStream, which are the component base classes we described above. Then, it is like the following categories: FileInputStream, StringBufferInputStream, and so on, they represent the concretecomponent described above, that is, decorative objects. In addition, InputStream also has filterinputstream this subclass, it is an abstract adornment, namely decorator, then its subclass: Bufferedinputstream, DataInputStream and so on is the concrete adornment person. So is it easier to understand Javaio from the point of view of the decorator model?

Below, we come to ourselves to realize the javaio of our own people. The function to implement is to capitalize the first letter of each word in a sentence. Let's start with a new class:Upperfirstwordinputstream.java

public class Upperfirstwordinputstream extends FilterInputStream {

    private int cbefore =;

    Protected Upperfirstwordinputstream (InputStream in) {
        //Because FilterInputStream has saved a reference to a decorated object, call super
        here directly Super (in);
    }

    public int read () throws ioexception{
        //Determines whether to capitalize
        int c = Super.read () based on whether the previous character is a space;
        if (Cbefore = =)
        {
            cbefore = C;
            return (c = = 1-c:character.touppercase ((char) c));
        else{
            cbefore = c;
            return c;
        }}}

Then write a test class:Inputtest.java

public class Inputtest {public

    static void Main (string[] args) throws IOException {
        int c;
        StringBuffer sb = new StringBuffer ();
        try {
            //Here are two decorators, respectively Bufferedinputstream and our Upperfirstwordinputstream
            inputstream in = new Upperfirstwordinputstream (New Bufferedinputstream) (New FileInputStream ("test.txt"));
            while ((c = in.read ()) >= 0)
            {
                sb.append ((char) c);
            System.out.println (SB);
        } catch (FileNotFoundException e) {
            e.printstacktrace ();}}}

(Note: The above Test.txt file needs to be created by yourself, placed in the same folder, content can be filled out at will.) )
Finally, let's look at the results of the operation:

Well, this article has introduced the decorator pattern in detail, I hope that readers can understand and apply to their own projects, thank you for your reading ~

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.