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.

Builder Pattern

Last updated at Posted at 2020-11-10

複雑なプログラムの組み合わせ(組成)を、user が意識することなく行うパターン
複数のコンストラクタが必要であったり、引数の数の組み合わせが多いするコンストラクタをプログラムの外部化する場合にも使える

このページではBuilder Patternについて記載します。

Design Pattarm MENU

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

クラス 説明
abstract Builder.class 複数メソッドを定義する
samBuilder1.class Builder.classを実装する
samBuilder2.class 同じ
Director.class Builderの複数メソッドを組成する
user(Main.class) 動作を確認
*user 他の開発者がこのパターンを利用する、という意味合いを含みます
Builder.class
abstract class Builder{
  abstract void line1();
  abstract void line2();
  abstract void msg(String msg);
}
samBuilder1.class
class samBuilder1 extends Builder{
  void line1(){System.out.println("|||||||||||||");}
  void line2(){System.out.println(".............");}
  void msg(String msg){System.out.println(msg);}
}
samBuilder2.class
class samBuilder2 extends Builder{
  void line1(){System.out.println("=============");}
  void line2(){System.out.println("~~~~~~~~~~~~~");}
  void msg(String msg){System.out.println(msg);}
}
Director.class
class Director{
  Builder builder;
  Director (Builder builder){this.builder=builder;}

  void construct(String msg){  // ここに複雑なコンストラクタを記述したり、メソッドを組み合わせる
    builder.line1();           // A
    builder.msg(msg);          // B
    builder.line2();           // C
  }                            // A~Cの順番を変えることで出力が変更する。メソッドを組み上げる例 
}
user(Main.class)
public static void main(String[] args){
  samBuilder1 sam1 = new samBuilder1();
  Director dc1 = new Director(sam1);
  dc1.construct("Builder");

  samBuilder2 sam2 = new samBuilder2();
  Director dc2 = new Director(sam2);
  dc2.construct("builder");
}}

userにはBuilderの具体的なメソッドは見えない

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?