Java decoration mode (decorator mode)

Source: Internet
Author: User

decorator often translated into "decoration", I think translated into "painter" more image point, painter (decorator) is used to brush paint, then painted objects we call decoratee. Both of these entities are required in the decorator mode.

Decorator definition: Dynamically adds some extra responsibilities to an object, like painting on a wall. It is more flexible to use the decorator mode to achieve the expansion of the function in the way of generating subclasses. Why use Decoratorwe can usually use inheritance to achieve the expansion of the function, if these need to expand the variety of functions, it is bound to generate a lot of subclasses, increase the complexity of the system, while the use of inheritance to achieve functional expansion, we must be able to foresee these expansion functions, these functions are compile-time determined, is static.

The reason for using decorator is that these features need to be dynamically decided by the user to join the way and timing. Decorator provides a "Plug and play" approach that determines when to add functionality during run time. How to use decorative mode example of piling in adapter, there are two species in adapter: Square pile Round Pile, adapter mode shows how to use these two classes in a comprehensive way, In the decorator mode, we are going to add some extra features to the piling, such as digging holes in the piles, and not caring how to use two unrelated classes.

We first set up an interface:
public interface work{
public void Insert ();
} The

interface work has a specific implementation: inserting a square pile or a circular pile, these two differences are indifferent to decorator. We take the insert square pile as an example:
public class Squarepeg implements work{
public void Insert () {
System.out.println ("square pile insert");
}
}

There is now an application: it is necessary to dig a pit before the pile is penetrated, to nail the planks on the pile after penetration, these additional functions are dynamic and may be arbitrarily added to the adjustment changes, for example, may need to be nailed to the shelves after piling (just metaphor).

Then we use the decorator mode, where the square pile squarepeg is decoratee (painted), we need to brush some "paint" on the decoratee, these paint is the extra function. public class Decorator implements work{
Private work work;
// Additional features are packaged in the list
Private ArrayList others = new ArrayList ();
//In the constructor, using the combined new method, the work object is introduced;
Public Decorator (  Work work) {
This.work=work;
Others.add ("Digging pits");
Others.add ("Nail Board");
}
public void Insert () {
Newmethod ();
}  
//In the new method, we add other methods before insert, where the order is the user's flexibility to specify
public void Newmethod () {
Othermethod ();
Work.insert ();  
}
public void Othermethod () {
Listiterator listiterator = Others.listiterator ();
  while (Listiterator.hasnext ()) {
System.out.println ((String) (Listiterator.next ()) + "in Progress");
}
}
} In the example above, we put the pits and the nailed planks in front of the piling insert, just to illustrate that the additional function order can be arbitrarily arranged.

Well, decorator mode comes out and we look at how to invoke:
Work squarepeg = new Squarepeg ();
Work decorator = new Decorator (squarepeg);
Decorator.insert ();

The decorator mode is now complete.

If you are careful, you will find that the call above is similar to the one we read from the file:
FileReader FR = new FileReader (filename);
BufferedReader br = new BufferedReader (FR);

In fact, Java I/O API is implemented using decorator, I/O variants are many, if all take the inheritance method, will produce many subclasses, obviously quite cumbersome. implementation of decorator in Jivein the forum system, some special words can not appear in the forum such as "Down xxx", we need to filter these "reactionary" fonts. Do not let them appear or display high brightness.

In the IBM Java column devoted to Jive's article, there is talk about jive in Forummessagefilter.java used decorator mode, in fact, the program does not really use decorator, Instead, it suggests that additional filtering capabilities can be designed for special forums, so you can reorganize forummessagefilter as decorator mode.

So, we are in the decorator mode, and will really use the decorator model, we must grasp the definition of decorator pattern, and the role of participation (Decoratee and decorator).


Decoration Mode Overview
    Add some extra responsibilities to an object dynamically. For added functionality, the decorator mode is more flexible than generating subclasses.
Applicability
    1. Add responsibilities to a single object in a dynamic, transparent manner without affecting other objects.    2. Handle the duties that can be undone.    3. When a method of generating subclasses cannot be used for expansion.
participants
    1.Component      defines an object interface that can dynamically add responsibilities to these objects.    2.ConcreteComponent      defines an object that can add some responsibility to the object.    3.Decorator      maintains a pointer to the component object and defines an interface that is consistent with the component interface.    4.ConcreteDecorator      Add responsibilities to the component.
class Diagram Example Component
Public interface Person {    void eat ();}
concretecomponent
Public class Mans implements person {public void eat () {System.out.println ("The Man is Eating");}}
Decorator
Public abstract class Decorator implements (person {    protected) person;        public void Setperson (person person) {        This.person = person;    }        public void Eat () {        person.eat ();    }}
Concretedecorator
public class Mandecoratora extends Decorator {public    void Eat () {        super.eat ();        Reeat ();        System.out.println ("Mandecoratora class");    }    public void Reeat () {        System.out.println ("Eat another Meal");}    
public class Mandecoratorb extends Decorator {public        void Eat () {        super.eat ();        System.out.println ("===============");        System.out.println ("Mandecoratorb class");}    }
Test
public class Test {public    static void Main (string[] args) {        mans man = New Man ();        Mandecoratora md1 = new Mandecoratora ();        Mandecoratorb MD2 = new Mandecoratorb ();                Md1.setperson (man);        Md2.setperson (MD1);        Md2.eat ();    }}
result
A man eats and eats another meal. Mandecoratora Class ===============mandecoratorb Class

Java adornment mode (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.