Wrap an object and extend the functionality of the wrapped object </ font>
In the sample code, instead of adding new functionality, I wrap the String object in parentheses.
Check with the following class structure
class | Explanation |
---|---|
abstract Display.class |
Common type for each class Define abstract method |
Message.class | Expand Display String field of this class is wrapped |
Decorator.class | Expand Display Implement Decorator |
user(Main.class) | Check the operation |
Below is the sample code
abstract_class_Display
abstract class Display{
abstract String getStr();
}
Message.class
class Message extends Display{
String msg;
Message(String s){this.msg=s;}
String getStr() {return msg;}
}
Decorder.class
class Decorator extends Display{
Display display;
StringBuffer sb = new StringBuffer();
Decorator(Display d){this.display=d;}
String getStr(){
return makeBorder(display.getStr());}
String makeBorder(String msg){
sb.append("<")
.append(msg)
.append(">");
return sb.toString();
}
}
user(Main.class)
public static void main(String[] args){
Display d1 = new Message("Hello java");
Display d2 = new Decorator(new Decorator(new Decorator(d1)));
System.out.println(d2.getStr());
}
Recommended Posts