「増補改訂版Java言語で学ぶデザインパターン入門」の「Chain of Responsibilityパターン」をC#で書いてみました。
GitHubにもコードを置いています。
参考
DesignPattern【Chain of Responsibility】GitHub
コード
public class Trouble
{
private int number;
public Trouble(int number)
{
this.number = number;
}
public int GetNumber()
{
return number;
}
public override string ToString()
{
return $"[Trouble {number}]";
}
}
public abstract class Support
{
private string name;
private Support next;
public Support(string name)
{
this.name = name;
}
public Support SetNext(Support next)
{
this.next = next;
return next;
}
public void DoSupport(Trouble trouble)
{
if (Resolve(trouble))
{
Done(trouble);
}
else if (next != null)
{
next.DoSupport(trouble);
}
else
{
Fail(trouble);
}
}
public override string ToString()
{
return $"[{name}]";
}
protected abstract bool Resolve(Trouble trouble);
protected void Done(Trouble trouble)
{
Console.WriteLine($"{trouble} is resolved by {this}");
}
protected void Fail(Trouble trouble)
{
Console.WriteLine($"{trouble} cannot be resolved.");
}
}
public class NoSupport : Support
{
public NoSupport(string name) : base(name)
{
}
protected override bool Resolve(Trouble trouble)
{
return false;
}
}
public class LimitSupport : Support
{
private int limit;
public LimitSupport(string name, int limit) : base(name)
{
this.limit = limit;
}
protected override bool Resolve(Trouble trouble)
{
if(trouble.GetNumber() limit)
{
return true;
}
else
{
return false;
}
}
}
public class OddSupport : Support
{
public OddSupport(string name) : base(name)
{
}
protected override bool Resolve(Trouble trouble)
{
if(trouble.GetNumber() % 2 == 1)
{
return true;
}
else
{
return false;
}
}
}
public class SpecialSupport : Support
{
private int number;
public SpecialSupport(string name, int number) : base(name)
{
this.number = number;
}
protected override bool Resolve(Trouble trouble)
{
if (trouble.GetNumber() == number)
{
return true;
}
else
{
return false;
}
}
}
class Program
{
static void Main(string[] args)
{
Support alice = new NoSupport("Alice");
Support bob = new LimitSupport("Bob", 100);
Support charile = new SpecialSupport("Charile", 429);
Support diana = new LimitSupport("Diana", 200);
Support elmo = new OddSupport("Elmo");
Support fred = new LimitSupport("Fred", 300);
alice.SetNext(bob).SetNext(charile).SetNext(diana).SetNext(elmo).SetNext(fred);
for(var i = 0; i 500; i += 33)
{
alice.DoSupport(new Trouble(i));
}
}
}
実行結果は以下のようになります。
[Trouble 0] is resolved by [Bob]
[Trouble 33] is resolved by [Bob]
[Trouble 66] is resolved by [Bob]
[Trouble 99] is resolved by [Bob]
[Trouble 132] is resolved by [Diana]
[Trouble 165] is resolved by [Diana]
[Trouble 198] is resolved by [Diana]
[Trouble 231] is resolved by [Elmo]
[Trouble 264] is resolved by [Fred]
[Trouble 297] is resolved by [Elmo]
[Trouble 330] cannot be resolved.
[Trouble 363] is resolved by [Elmo]
[Trouble 396] cannot be resolved.
[Trouble 429] is resolved by [Charile]
[Trouble 462] cannot be resolved.
[Trouble 495] is resolved by [Elmo]
その他のデザインパターンは以下の記事から確認してください。