anomalocaristan’s blog

JSやGo、設計などについて学んだことをメモしておくサイトです

【デザインパターンノック】1本目 Abstract Factory <<WIP>>

概要

  • インスタンスを生成する為だけのクラス。このクラスが持つ責務は インスタンスを生成する ということだけ
  • オブジェクトグループを間違いなく生成する

もっとわかりやすく

例えば、下記のように3つのオブジェクトがあるとする。

f:id:anomalocaristan:20200826013043p:plain
オブジェクト一覧

Goで書くとこんな感じ

type dog struct {
    favoriteFood string
}

type cat struct {
    favoriteFood string
}

type man struct {
    favoriteFood string
}

さらに、 好物のオブジェクト を作るための構造体と関数も用意する。

type food struct {
    ingredients string
}

func NewTakoyaki(ingredients string) food {
    return food{ingredients: ingredients}
}

本来期待する動作は、 キャラクターに対して適切な好物を設定する ということ。 ↓ なら特に問題ないけど(たこ焼き食べたい)

func main() {
    man := NewMan(NewTakoyaki("octopus"))
}

↓の場合は犬の健康に悪影響が出てしまう。

func NewCat(favoriteFood food) food {
    return food{ingredients: favoriteFood.ingredients}
}

それで結局何なのか

キャラクター・フードのインスタンス作成を

参考

Abstract Factory パターン - Wikipedia

8. AbstractFactory パターン | TECHSCORE(テックスコア)