I am trying to demonstrate use of chain of responsibility pattern by searching characters/ string inside Servicer class strings. The code runs but Servicer1 ServiceReq is not calling Servicer2 ServiceReq. If I run this with "g", I get"Checked Servicer1'" only but I should get "Checked Servicer1'" "Request found in Servicer 2".
MainApp.cs
namespace ChainOfResponsibility
{
abstract class Servicer
{
protected Servicer successor;
public void SetSuccessor( Servicer s)
{
successor = s;
}
public abstract string ServiceReq(char request);
}
class Servicer1 : Servicer
{
public override string ServiceReq(char request)
{
string s1 = "Sam ate nuts";
if (s1.Contains(request))
{
return "Request found in Servicer 1";
}
else if (successor != null)
{
successor.ServiceReq(request);
}
return "Checked Servicer1'";
}
}
class Servicer2 : Servicer
{
public override string ServiceReq(char request)
{
string s2 = "Apples are great";
if (s2.Contains(request))
{
return "Request found in Servicer 2";
}
else if (successor != null)
{
successor.ServiceReq(request);
}
return "Checked Servicer 2";
}
}
Form Code:
namespace ChainOfResponsibility
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
char request = System.Convert.ToChar(textBox1.Text);
Servicer h1 = new Servicer1();
Servicer h2 = new Servicer2();
h1.SetSuccessor(h2);
AddToList(h1.ServiceReq(request));
}
private void AddToList(string message)
{
listBox1.Items.Add(message);
listBox1.Items.Add("----------------------------------------");
if (listBox1.Items.Count > 0)
listBox1.TopIndex = listBox1.Items.Count - 1;
}
}
}