A chain of objects is addressed by a request sent by the originator in chain of responsibility. Any element in the chain is capable of processing the request.
The Chain of Responsibility Pattern states, "Allow multiple objects the opportunity to handle the request in order to prevent coupling the sender and receiver of the request." An ATM, for instance, implements the Chain of Responsibility design pattern in its money-dispensing procedure.
Alternatively stated, it can be stated that references to other receivers are typically present in each receiver. If an object is unable to process a request, it forwards it to the subsequent receiver, and so forth.
One benefit of chain of responsibility pattern advertisements is their effectiveness.
- A reduction in coupling is achieved.
- It enhances adaptability in the process of delegating duties to entities.
- It enables a collection of classes to function as a single entity; composition enables the transmission of events generated in one class to other controller classes.
Implementing the Chain of Responsibility Framework:
- When the handler of a request that can be processed by more than one object is unknown.
- In situations where the group of objects capable of processing the request must be dynamically specified.
Source code of Logger.java
package com.t4b.test.java.dp.bp.cor;
abstract class Logger {
protected Logger nextLogger;
public void setNextLogger(Logger nextLogger) {
this.nextLogger = nextLogger;
}
public void logMessage(String message) {
log(message);
if (nextLogger != null) {
nextLogger.logMessage(message);
}
}
abstract protected void log(String message);
}
Source code of FileLogger.java
package com.t4b.test.java.dp.bp.cor;
class FileLogger extends Logger {
public FileLogger() {
}
@Override
protected void log(String message) {
System.out.println("FileLogger: " + message);
}
}
Source code of EMailLogger.java
package com.t4b.test.java.dp.bp.cor;
class EMailLogger extends Logger {
public EMailLogger() {
}
@Override
protected void log(String message) {
System.out.println("EMailLogger: " + message);
}
}
Source code of ConsoleLogger.java
package com.t4b.test.java.dp.bp.cor;
class ConsoleLogger extends Logger {
public ConsoleLogger() {
}
@Override
protected void log(String message) {
System.out.println("ConsoleLogger: " + message);
}
}
Source code of TestMain.java
package com.t4b.test.java.dp.bp.cor;
public class TestMain {
private static Logger getChainOfLoggers() {
Logger emailLogger = new EMailLogger();
Logger fileLogger = new FileLogger();
Logger consoleLogger = new ConsoleLogger();
emailLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
return emailLogger;
}
public static void main(String[] args) {
Logger loggerChain = getChainOfLoggers();
loggerChain.logMessage("Message-1");
System.out.println();
loggerChain.logMessage("Message-2");
System.out.println();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.