Skip to content

Instantly share code, notes, and snippets.

@arakaki-asdf
Last active October 27, 2019 01:01
Show Gist options
  • Save arakaki-asdf/41dc7514ce9d8dab36f198e74920454e to your computer and use it in GitHub Desktop.
Save arakaki-asdf/41dc7514ce9d8dab36f198e74920454e to your computer and use it in GitHub Desktop.
Strategyパターン

Strategyパターン

メリット

if文などで分岐して処理を変更する部分をクラスで分けることで、比較的にアルゴリズムの追加が簡単になり、メンテナンスしやすい設計になる。

デメリット

分岐する処理が少ないなら分けないほうがシンプル。

流れ

  • 1 アルゴリズムをクラスに分割して、共通のインターフェイスを利用する。
  • 2 利用する側では、行いたい処理のクラスを渡す。

例) Humanをheight, weight, ageで比較する処理をStrategyパターンで分ける

public class Human
{
    public string name;
    public int height;
    public int weight;
    public int age;
}

public class SampleController
{
    IComparator comp;

    public SampleController(IComparator comp)
    {
        this.comp = comp;
    }

    // 大小を比較
    public int compare(Human h1, Human h2)
    {
        return comp.compare(h1, h2);
    }
}

public interface IComparator
{
    int compare(Human h1, Human h2);
}


public class AgeComparator : IComparator
{
    public int compare(Human h1, Human h2)
    {
        if (h1.age > h2.age) return 1;
        else if (h1.age == h2.age) return 0;
        return -1;
    }
}
public class HeightComparator : IComparator
{
    public int compare(Human h1, Human h2)
    {
        if (h1.height > h2.height) return 1;
        else if (h1.height == h2.height) return 0;
        return -1;
    }
}
public class WeightComparator : IComparator
{
    public int compare(Human h1, Human h2)
    {
        if (h1.weight > h2.weight) return 1;
        else if (h1.weight == h2.weight) return 0;
        return -1;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment