Chain of Responsibility Pattern in Java

Chain of Responsibility Pattern is a Behavioral Pattern in which, a Request is sent through a chain of handling Objects without knowing which Object will handle it. With Chain of Responsibility Pattern, we can avoid coupling the Sender of a request to received Objects and create a processing sequence automatically based on type of request.

I. OVERVIEW

Chain of Responsibility Pattern defines a set of Handlers that receive request from Sender. Each Handler processes it if possible or pass to another Handler, or does both: process and pass it on.
chain-of-responsibility-overview-
This is a simple diagram of the Pattern:
chain-of-responsibility-diagram
– We have an Abstract Handler class that contains inner Successor and handle method for processing Request and pass it to another Successor.
– All Handlers extend Abstract Handler class. Each Handler sets its own Successor (the next Handler).
– Client just gives Request for the first Handler to process, next Handler will handle Request automatically anytime it receives.

II. PRACTICE

1. Project Overview

The customer has a problem with a specific level of difficulty. We have 3 people with different standards: Regular Developer, Senior and Expert. Depending on the problem level, we choose person to give customer advice. So we pass problem (level) to Regular Developer first, if he is not qualified enough to solve the problem (his level is not equal problem level), he will pass the problem to people who has higher standard, and so on.
chain-of-responsibility-demo

2. Step by Step

2.1- Create AbstractConsultant class:


package com.javasampleapproach.chainofresponsibility.pattern;

public abstract class AbstractConsultant {

	protected int level;

	protected AbstractConsultant nextConsultant;

	public void setNextConsultant(AbstractConsultant nextConsultant) {
		this.nextConsultant = nextConsultant;
	}

	public void giveAdvice(int level) {

		if (this.level >= level) {
			advise(level);
		} else {
			nextConsultant.giveAdvice(level);
		}
	}

	abstract protected void advise(int level);
}

2.2- Create ProblemLevel enum:


package com.javasampleapproach.chainofresponsibility.pattern;

public enum ProblemLevel {
	EASY(1), NORMAL(2), COMPLEX(3), DIFFICULT(4), HARD(5), VERYHARD(6), INSANE(7);
	private int value;

	private ProblemLevel(int value) {
		this.value = value;
	}

	public int value() {
		return value;
	}
}

2.3- Create some Handlers class that extend AbstractConsultant class:
RegularDeveloper can give advice for problem level up to 2, Senior is up to 5, and Expert is up to 7.

RegularDeveloper.java


package com.javasampleapproach.chainofresponsibility.pattern;

public class RegularDeveloper extends AbstractConsultant {

	public RegularDeveloper() {
		this.level = 2;
	}
	
	@Override
	protected void advise(int level) {
		System.out.println("RegularDeveloper helps to solve problem level " + level);
	}
}

Senior.java


package com.javasampleapproach.chainofresponsibility.pattern;

public class Senior extends AbstractConsultant {

	public Senior() {
		this.level = 5;
	}
	
	@Override
	protected void advise(int level) {
		System.out.println("Senior helps to solve problem level " + level);
	}
}

Expert.java


package com.javasampleapproach.chainofresponsibility.pattern;

public class Expert extends AbstractConsultant {

	public Expert() {
		this.level = 7;
	}

	@Override
	protected void advise(int level) {
		System.out.println("Expert helps to solve problem level " + level);
	}
}

2.4- Create Client Test Class:


package com.javasampleapproach.chainofresponsibility;

import com.javasampleapproach.chainofresponsibility.pattern.AbstractConsultant;
import com.javasampleapproach.chainofresponsibility.pattern.Expert;
import com.javasampleapproach.chainofresponsibility.pattern.ProblemLevel;
import com.javasampleapproach.chainofresponsibility.pattern.RegularDeveloper;
import com.javasampleapproach.chainofresponsibility.pattern.Senior;

public class MainApp {

	public static void main(String[] args) {
		
		AbstractConsultant developer = new RegularDeveloper();
		AbstractConsultant senior = new Senior();
		AbstractConsultant expert = new Expert();
		
		developer.setNextConsultant(senior);
		senior.setNextConsultant(expert);
		
		System.out.println("--- ProblemLevel = NORMAL ---");
		ProblemLevel difficultLevel = ProblemLevel.NORMAL;
		developer.giveAdvice(difficultLevel.value());
		
		System.out.println("--- ProblemLevel = DIFFICULT ---");
		difficultLevel = ProblemLevel.DIFFICULT;
		developer.giveAdvice(difficultLevel.value());
		
		System.out.println("--- ProblemLevel = INSANE ---");
		difficultLevel = ProblemLevel.INSANE;
		developer.giveAdvice(difficultLevel.value());
	}
}

2.5- Run the code, the console window shows:


--- ProblemLevel = NORMAL ---
RegularDeveloper helps to solve problem level 2
--- ProblemLevel = DIFFICULT ---
Senior helps to solve problem level 4
--- ProblemLevel = INSANE ---
Expert helps to solve problem level 7

III. SOURCE CODE

ChainOfResponsibilityPattern

46 thoughts on “Chain of Responsibility Pattern in Java”

  1. An intriguing discussion is definitely worth
    comment. I do think that you need to write more on this topic, it may not be a taboo subject but usually
    folks don’t speak about these subjects. To the next!

    Cheers!!

  2. Hi superb website! Does running a blog like this take a large amount of work?
    I have very little knowledge of programming however I had been hoping
    to start my own blog in the near future. Anyway, should you have any ideas or techniques
    for new blog owners please share. I understand this is off subject but I just needed to ask.
    Thanks!

  3. Good post. I learn something new and challenging on websites I stumbleupon everyday.
    It will always be useful to read articles from other writers and practice a little something from other sites.

  4. Unquestionably imagine that which you stated. Your favorite reason seemed to be
    on the web the simplest factor to bear in mind of. I say to you,
    I certainly get irked even as folks consider issues that they just don’t realize about.

    You controlled to hit the nail upon the top and also defined out the entire thing without having side
    effect , people can take a signal. Will probably
    be again to get more. Thank you

  5. Currently it looks like Expression Engine is the top blogging platform out
    there right now. (from what I’ve read) Is that
    what you’re using on your blog?

  6. My programmer is trying to persuade me to move to .net from PHP.

    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on a number
    of websites for about a year and am worried about switching to another platform.
    I have heard good things about blogengine.net. Is there a way I can import all my wordpress content into it?
    Any help would be really appreciated!

  7. You could certainly see your expertise in the work you write.
    The sector hopes for more passionate writers such as you who are not afraid to say how they believe.
    At all times follow your heart.

  8. I’ve been browsing online greater than three hours lately, but I
    by no means found any fascinating article like yours. It’s
    pretty value enough for me. Personally, if all site owners and bloggers
    made good content as you did, the net will be much more useful than ever before.

  9. Hey! Would you mind if I share your blog with my facebook group?
    There’s a lot of folks that I think would really appreciate your
    content. Please let me know. Many thanks

  10. I was very pleased to find this site. I wanted to thank you for your time due to
    this fantastic read!! I definitely enjoyed
    every little bit of it and i also have you book marked to check out new information in your web site.

  11. Pretty nice post. I just stumbled upon your blog and wanted to mention that I have truly
    loved surfing around your blog posts. In any case I will be subscribing in your rss feed and I’m hoping you
    write once more very soon!

  12. Its such as you learn my mind! You seem to know so much approximately this, like you
    wrote the book in it or something. I believe that you could
    do with some % to power the message home a bit,
    however other than that, that is wonderful blog.
    An excellent read. I’ll definitely be back.

  13. An impressive share! I have just forwarded this onto a colleague who was doing
    a little research on this. And he actually bought me lunch due to the fact that I stumbled upon it
    for him… lol. So allow me to reword this….

    Thank YOU for the meal!! But yeah, thanks for spending the time to discuss this issue here on your blog.

  14. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each
    time a comment is added I get four emails
    with the same comment. Is there any way you can remove
    me from that service? Cheers!

  15. I seriously love your website.. Very nice colors & theme.
    Did you develop this website yourself? Please reply back as I’m trying to create my
    own blog and want to find out where you got this from or exactly what the theme
    is named. Cheers!

  16. I loved as much as you’ll receive carried out right here.

    The sketch is attractive, your authored subject
    matter stylish. nonetheless, you command get bought
    an nervousness over that you wish be delivering the following.
    unwell unquestionably come further formerly again as exactly the same
    nearly very often inside case you shield this increase.

  17. Hi there! This blog post couldn’t be written any better!

    Looking through this article reminds me of my previous roommate!
    He continually kept talking about this. I will forward this article to him.
    Fairly certain he’ll have a good read. Many thanks for sharing!

  18. fantastic issues altogether, you just received a emblem new reader.
    What might you recommend about your publish that you simply made a few days in the past?

    Any positive?

  19. Hi there would you mind letting me know which hosting company you’re using?

    I’ve loaded your blog in 3 different web browsers and I must say
    this blog loads a lot quicker then most. Can you suggest a good web hosting provider
    at a honest price? Many thanks, I appreciate it!

  20. Superb site you have here but I was wanting to know if you knew of any message boards that cover the
    same topics discussed in this article? I’d really
    love to be a part of community where I can get suggestions from other
    knowledgeable people that share the same interest.
    If you have any recommendations, please let me know.
    Many thanks!

  21. Sweet blog! I found it while searching on Yahoo News.
    Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a
    while but I never seem to get there! Cheers

  22. Wow! This blog looks just like my old one! It’s on a entirely different topic but it
    has pretty much the same page layout and design. Great choice of colors!

  23. We are a gaggle of volunteers and opening a brand new scheme in our
    community. Your web site provided us with helpful info to work on. You have performed a
    formidable job and our entire group might be thankful to
    you.

  24. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored material stylish.
    nonetheless, you command get got an edginess
    over that you wish be delivering the following. unwell
    unquestionably come more formerly again as exactly the same nearly a lot often inside case you shield
    this increase.

  25. It’s a shame you don’t have a donate button! I’d without
    a doubt donate to this excellent blog! I guess for now i’ll
    settle for bookmarking and adding your RSS feed to my Google account.
    I look forward to brand new updates and will share this site
    with my Facebook group. Chat soon!

  26. Great items from you, man. I’ve take note your stuff prior to and you are simply extremely magnificent.
    I really like what you’ve bought right here, certainly like
    what you are stating and the way in which you are saying it.

    You make it enjoyable and you continue to care
    for to keep it sensible. I can not wait to read far more from you.
    This is actually a tremendous website.

  27. Great blog! Do you have any tips for aspiring writers? I’m hoping to start
    my own site soon but I’m a little lost on everything. Would you advise starting
    with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely confused ..

    Any ideas? Thanks!

  28. I’m not sure why but this web site is loading extremely
    slow for me. Is anyone else having this problem or is it a issue on my end?
    I’ll check back later on and see if the problem still exists.

  29. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.

    You definitely know what youre talking about,
    why throw away your intelligence on just posting videos to your weblog when you could be
    giving us something informative to read?

  30. Howdy just wanted to give you a quick heads up and let you know a few of
    the images aren’t loading correctly. I’m not sure why but I think its a linking issue.

    I’ve tried it in two different browsers and both show the
    same outcome.

Leave a Reply

Your email address will not be published. Required fields are marked *