2
0

More than 1 year has passed since last update.

初心者でもわかるBuilderパターン Builderパターンでカレーを作くろう!!

Posted at

はじめに

皆さんはBuilderパターンをご存知でしょうか。
Builderパターンには色々な種類ありますが、今回はGoFのBuilderパターンについて解説していきます。

GoFのBuilderパターンとは

Builder パターン(ビルダー・パターン)とは、GoF(Gang of Four; 4人のギャングたち)によって定義されたデザインパターンの1つです。 オブジェクトの生成過程を抽象化することによって、動的なオブジェクトの生成を可能にします。(引用 wikipedia)

分かりやすく言うなら、猫というクラスがあるとします。猫の抽象的な概念は動物ですよね。
この場合、猫クラスから犬クラスに変わったとしても対応できますよね。
どうでしょうか?イメージが湧いたでしょうか。サンプルコード通してどんなものか具体的に説明していきます。

クラス図

スクリーンショット 2022-02-15 20.51.18.png

サンプルコード

いきなりですが、皆さんは冷蔵庫の中に玉ねぎ、にんじん、ポテト、お肉、カレールーがあったら、何を作りますか?そう!!カレーですよね。では、カレーを作っていきましょう。

まずは、材料量の入った冷蔵庫を作成します。


mojikyo45_640-2.gif

Fridge.java
public enum Fridge {
    ONION ,CARROT,CURRYSAUCEMIX,POTATO ,METTO
}

先程Briderパターンについて説明した抽象的なクラスを作っていきます。
ここではカレーの抽象的な概念として料理クラスを作成していきます。
これが出来れば、肉じゃがに変更しても対応できるようになります。

Cooking.java
public class Cooking {
    private Fridge food1;
    private Fridge food2;
    private Fridge food3;

    void setFood1(Fridge f) {
        this.food1 = f;
    }
    void setFood2(Fridge f) {
        this.food2 = f;
    }
    void setFood3(Fridge f) {
        this.food3 = f;
    }
    //,,,

    public String toString() {
        return "[food1:" + this.food1 + ", food2:" + this.food2 + ", food3:" + this.food3 + "]";
    }
}

レシピがないと料理人が勝手にアレンジをしてしまうのでレシピを作っていきます。
ここでは、抽象メソッドを定義していきます。


mojikyo45_640-2.gif

Recipe.java
public interface Recipe {
    void cook1();
    void cook2();
    void cook3();
    Cooking getResult();
}

皆さんお待たせいたしました。お待ちかねのカレーを作っていきましょう。
レシピ通りにカレーを作っていきましょう。
また、コンストラクタにはCookingをインスタンス化してオブジェクトに必要な材料を詰めてあげます。
要するに料理という抽象的な概念から、カレーを料理するという具体的な概念に落とし込むということです。


mojikyo45_640-2.gif

Curry.java
public class Curry implements Recipe {
    private Cooking cooking;
    Curry(){
        this.cooking = new Cooking();
    }
    public void cook1() {
        this.cooking.setFood1(Fridge.ONION);
    }
    public void cook2() {
        this.cooking.setFood2(Fridge.METTO);
    }
    public void cook3() {
        this.cooking.setFood3(Fridge.CURRYSAUCEMIX);
    }
    public Cooking getResult() {
        return this.cooking;
    }
}

仕上げに盛り付けていきましょう。
platingメソッドを使うことで、料理してきたものが形になります。

Cooker.java
public class Cooker {
    private Recipe recipe;
    Cooker (Recipe recipe){
        this.recipe=recipe;
    }
    Cooking plating() {
        this.recipe.cook1();
        this.recipe.cook2();
        this.recipe.cook3();
        return this.recipe.getResult();
    }
}

完成です。

Test.java
public class Test {
    public static void main(String[] args) {
        Cooker w = new Cooker(new Curry());
        Cooking c = w.plating();
        System.out.println(c);
    }
}

終わりに

めちゃくちゃなサンプルコードですが、皆さんはbuilderクラスについてお分かり頂けたでしょうか。わからない方は実際に手を動かしてみると分かってくるのでお勧めです。
最後まで読んで頂きありがとうございます。

2
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
2
0