Search

Chain of responsibility

Chain of responsibility

Chain of responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.[1] Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.

A mechanism also exists for adding new processing objects to the end of this chain. Thus, the chain of responsibility is an object oriented version of the if ... else if ... else if ....... else ... endif idiom, with the benefit that the condition–action blocks can be dynamically rearranged and reconfigured at runtime.

public class iMessage
{
	public string Sender { get; set; }
	public string Receiver { get; set; }
	public string Message { get; set; }
}


public abstract class IHandler
{
    protected iMessage incomingMessage;
    public Func<bool> Condition;
    public Predicate<int> Condition2;
    public IHandler Sucessor { get; set; }

    public IHandler(iMessage msg)
    {
        this.incomingMessage = msg;
    }

    public IHandler ChainWith(IHandler nextIHandler)
    {
        Sucessor = nextIHandler;
        return Sucessor;
    }

    public abstract void HandleMessage();
}

public class Handler1 : IHandler
{
    public Handler1(iMessage msg) : base(msg) { }
   
    public override void HandleMessage()
    {
        if (Condition())
        {
            Console.WriteLine("EBE IHandler Called" + incomingMessage.iMessageHeader.MessageId); 
        }
        else
        {
            Sucessor.HandleMessage();
        }
    }
}

public class Handler2 : IHandler
{
    public Handler2(iMessage msg) : base(msg) { }
   

    public override void HandleMessage()
    {
        if (Condition())
        {
            Console.WriteLine("TOK IHandler Called" + incomingMessage.iMessageHeader.MessageId);
        }
        else
        {
            Sucessor.HandleMessage();
        }
    }
}

public class ErrorHandler : IHandler
{
	MessageCache messageCache;
	public ErrorHandler(iMessage msg) : base(msg)
	{
		messageCache = new MessageCache(msg);
	}
   

	public override void HandleMessage()
	{
		messageCache.Save("Error", "Error ");
		Console.WriteLine("Error Handler Called" + incomingMessage.MessageHeader.MessageId);
	}
}

public class Test{
	public static void test2(iMessage gm)
	{
		IHandler h1 = new Handler1(gm);
		h1.Condition = () => gm.iMessageHeader.Sender == "abc@email.com";
		
		IHandler h2 = new Handler2(gm);
		h2.Condition = () => gm.iMessageHeader.Sender == "def@email.com" && gm.iMessageHeader.Receiver == "abc@email.com";

		IHandler h3 = new ErrorHandler(gm);
		h3.Condition = () => gm.iMessageHeader.Sender != "ghi@email.com" && gm.iMessageHeader.Receiver != "def@email";


		h1.Sucessor = h2;            
		h2.Sucessor = h3;

		//h1.ChainWith(h2).ChainWith(h3);

		h1.HandleMessage();
	}

}