Decorator mode
Decorator Mode (alias wrapper): Dynamically attaches responsibilities to objects, and to extend functionality, decorators provide a more resilient alternative than inheritance.
The decorator has a common superclass with the decorator, and the purpose of inheritance is to inherit the type, not the behavior
Now, for example, there is a way to filter text.
1. Interface:
Package Com.qiao.wrapper; Public Interface Messageboardhandler { public string Filter (String msg);}
2. Successors
Package Com.qiao.wrapper; Public class Implements messageboardhandler{ public string Filter (String msg) { return ] Process the content on the message board: "+msg; }}
3. Call
@Test Public void test4 () { new messageboard (); = Hanlder.filter ("<a>hello</a>"); SYSTEM.OUT.PRINTLN (msg);}
Console output
Now I have a need, I want to filter the message board inside the label, but I do not want to change the original method.
At this point, one way is to wrap a layer outside of the method
1. Write a wrapper class, also implement Messageboardhandler this interface
PackageCom.qiao.wrapper; Public Abstract classMessageboarddecoratorImplementsmessageboardhandler{PrivateMessageboardhandler Handler; Publicmessageboarddecorator (Messageboardhandler hanlder) { This. handler=Hanlder; } Publicstring Filter (String msg) {return This. Handler.filter (msg); }}
2. Write an HTML tag filter class, inherit this wrapper class
PackageCom.qiao.wrapper; Public classHtmlfilterextendsMessageboarddecorator {PrivateMessageboardhandler Hanlder; PublicHtmlfilter (Messageboardhandler hanlder) {Super(Hanlder); This. hanlder=Hanlder; } Publicstring Filter (String msg) {String temp= This. Hanlder.filter (msg); Temp+ = "^^ ^filter HTML Tag"; returntemp; }}
3. Call
@Test publicvoid test5 () { new htmlfilter (new messageboard ()); = Dec.filter ("<a>hello</a>"); SYSTEM.OUT.PRINTLN (msg); }
Output
Join I do not want to filter the HTML tag now, I want to filter some sensitive words, this is I just wrapped in the original method of another method can be
PackageCom.qiao.wrapper; Public classSensitivefilterextendsMessageboarddecorator {PrivateMessageboardhandler Hanlder; PublicSensitivefilter (Messageboardhandler hanlder) {Super(Hanlder); This. Hanlder =Hanlder; } Publicstring Filter (String msg) {String temp= This. Hanlder.filter (msg); Temp+ = "Filter Sensitive words"; returntemp; }}
Call
@Test publicvoid Test6 () { new sensitivefilter ( New messageboard ()); = Dec.filter ("<a>hello</a>"); SYSTEM.OUT.PRINTLN (msg); }
Output
Process the content on the message board:<a>hello</a> filter sensitive words
Personal understanding, in fact, is in the original method of packaging a layer of methods to achieve their own purposes, which in Java IO in a large number of use of the wrapper mode
Decorator mode Learning for Java design patterns