Chain Of Responsibility
Often there comes a time where you need to make interact with an object that happens to have restricted access. Beginner way to do it, is to make every method and prop public, while expert way is to use a chain of responsibility.
Chain of Responsibility is a pattern where a request gets passed on between Handlers until the proper one found to handle it. The creation purpose of this mechanism is create an enviroment where a request/proccess can find it’s handler with out comprimising encapsulation.
Prevents the sender to explicitly defining the handler, creating a intelligent mechanism if done correctly while preserving encapsulation.
Object becomes the responsibility of the chain until someone handles it.
Here is an example of how. First we create a Request class to act as… well a request.
Here is the abstract Handler class to be extended by Concrete Handlers.
As you can see for this example i’ve created a static ArrayList to register all the Handler implementations that are created. This way whenever you extend Handler calling the super constructor will add it to the chain automaticly. Lets see the concrete handlers now.
As you can each Handler implementation handles the request as they please and if they do not then pass it to the successor.
Lets see the main method now: