0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Decorator Pattern

Last updated at Posted at 2020-11-12

オブジェクトをラップし、ラップしたオブジェクトの機能を拡張する

Design Pattarm MENU

サンプルコードでは、新しく機能を追加する代わりに、Stringオブジェクトをカッコでラップします

以下のクラス構成で確認します

クラス 説明
abstract
Display.class
各クラスの共通型とする
抽象メソッドを定義
Message.class Displayを拡張
このクラスのStringフィールドがラップ対象
Decorator.class Displayを拡張
Decoratorを実装する
user(Main.class) 動作を確認する

*user 他の開発者がこのパターンを利用する、という意味合いを含みます

以下はサンプルコードです

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());
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?