Chain of Responsibility Design Pattern

By Hikmet Cakir

Chain of Responsibility Design Pattern

Chain of responsibility is a behavioral design pattern. This design pattern provides that your request that was created pass respectively to a chain of handlers and each handler decides a decision about the request that is taken. Each handler decides either to process the request or to pass it to the next handler in the chain.


This design pattern is generally used in operations that have to do respectively. For instance, let’s suppose that we have an input panel and this panel accepts only valid words. The deciding this operation uses some conditions. The conditions for an word ​​to be valid are :


— The word must not be null or blank.

— The word mustn’t contain special charaters such as ‘#’, ‘$’, ‘_’ and ‘.’ etc.

—The word must be created from only characters.


This design pattern should be used in this and similar structures.

How To Implement

  1. Create an abstract class. This class should contains the created class’s field, a linking method for create a chain and one abstract method that is used by handlers for decisiding related with request and latest one is a concrite method that is used for move in chain.
  2. Create concrite handler classes that extends abstract class then abstract method should be implemented by logic and if handler isn’t used for request’s process, it calls other chain’s handler.
  3. The latest one, client side should set about which handlers should be added to chain and how handlers should be line.


Example Implementation

I had mentioned before about an example of given the word’s validation. Let’s do it. Firstly, an abstract class should be created and this class should contains some methods so I defined an abstract class that name is StringValidator.


public abstract class StringValidator {


    private StringValidator next;


    public static StringValidator link(StringValidator first, StringValidator... chain) {
        StringValidator head = first;
        for(StringValidator nextInChain : chain) {
            head.next = nextInChain;
            head = nextInChain;
        }
        return first;
    }


    public abstract boolean check(String value);


    protected boolean checkNext(String value) {
        if(next == null) {
            return true;
        }
        return next.check(value);
    }
}

Secondly, we should define handlers so I defined all handlers which names are BlankStringValidator, CharacterStringValidator and the latest one SpecialCharacterStringValidator.

public class BlankStringValidator extends StringValidator {


    @Override
    public boolean check(String value) {
        if(value == null || value.isBlank()) {
            return false;
        }
        return checkNext(value);
    }
}


import java.util.regex.Pattern;


public class CharacterStringValidator extends StringValidator {


    @Override
    public boolean check(String value) {
        if (!Pattern.matches("[a-zA-Z]+", value)) {
            return false;
        }
        return checkNext(value);
    }
}


import java.util.regex.Pattern;


public class SpecialCharacterStringValidator extends StringValidator {


    @Override
    public boolean check(String value) {
        if (Pattern.matches(".*[\\p{Punct}].*", value)) {
            return false;
        }
        return checkNext(value);
    }
}


Thirdly, we should set about which handlers should be added to chain and how handlers should be line.

public class Demo {


    public static void main(String[] args) {
        StringValidator[] chain = { new CharacterStringValidator(), new SpecialCharacterStringValidator() };
        StringValidator first = new BlankStringValidator();
        StringValidator stringValidator = StringValidator.link(first, chain);


        boolean numberOne = stringValidator.check(null);
        System.out.println("Number One=" + numberOne);


        boolean numberTwo = stringValidator.check("快乐的时光");
        System.out.println("Number Two=" + numberTwo);


        boolean numberThree = stringValidator.check("1Hello2World3");
        System.out.println("Number Two=" + numberThree);


        boolean numberFour = stringValidator.check("#Hello*World$");
        System.out.println("Number Three=" + numberFour);


        boolean numberFive = stringValidator.check("HelloWorld");
        System.out.println("Number Four=" + numberFive);
    }
}

CLI Output

Number One=false
Number Two=false
Number Two=false
Number Three=false
Number Four=true

I hope everything’s clear for you. If you don’t understand any part, feel free ask me. Also, I shared the codes I explained and more in GitHub. Additionally, certainly I recommend that you should practice with this structures. I coded these structures and these structures’ some test scenarios. You can check out to repository.

I used various resource for prepare this essay. I indicated in following. You can check out.