if文などで分岐して処理を変更する部分をクラスで分けることで、比較的にアルゴリズムの追加が簡単になり、メンテナンスしやすい設計になる。
分岐する処理が少ないなら分けないほうがシンプル。
- 1 アルゴリズムをクラスに分割して、共通のインターフェイスを利用する。
- 2 利用する側では、行いたい処理のクラスを渡す。
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;
}
}