Decorator Pattern

Wrap an object and extend the functionality of the wrapped object </ font>

Design Pattarm MENU

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
  • User Includes the meaning that other developers use this pattern

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

Decorator pattern
Decorator Pattern
Design pattern ~ Decorator ~
Prototype pattern
Memento Pattern
Mediator pattern
Iterator pattern
Composite pattern
Builder pattern
Bridge Pattern
Command Pattern
Builder Pattern
Strategy pattern
Iterator Pattern
Visitor pattern
Proxy Pattern
Composite Pattern
Singleton Pattern
Singleton pattern
Prototype Pattern
Facade Pattern
Mediator Pattern
Facade pattern
Visitor Pattern
Bridge pattern
Design pattern ~ Builder ~
[Java] Strategy pattern
Design pattern ~ Visitor ~
Java design pattern
java callback pattern
Design pattern ~ Proxy ~
Design pattern ~ State ~
Factory Method Pattern
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (2): Builder
Design pattern (1): AbstractFactory
[Java] Singleton pattern
Design pattern ~ Command ~
Abstract Factory pattern
Design pattern ~ Iterator ~
Design pattern ~ Facade ~
Design pattern ~ Bridge ~
Design pattern ~ Mediator ~
Template Method Pattern
Design pattern ~ Interpreter ~
Factory Method pattern
Design pattern ~ Observer ~
Design pattern ~ Prototype ~
[Java] Adapter pattern
Design pattern ~ Memento ~
Design pattern ~ Adapter ~
Design pattern ~ Flyweight ~
Java pattern memo
Refactor the Decorator pattern implementation with a functional interface