Advertisement
Oppenheimer

Chain of responsibility design pattern

Mar 8th, 2025
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. import java.util.*;
  2. import java.time.*;
  3.  
  4. /*
  5.  * Client -> request handler 1 -> request handler 2 -> request handler 3
  6.  * Withraw 2000rs from atm -> 2000 rs handler -> 500 rs handler -> 100 rs handler and so on
  7.  *
  8.  * chain of responsibility : validate username -> check atm pin -> then check atm expiry date-> check user balance -> then give money ...
  9.  *
  10.  */
  11.  
  12. /*
  13.  * basically means ki agar info logging ka call aae and info logger na mile to
  14.  * error logging kardo
  15.  *
  16.  */
  17.  
  18. abstract class LogProcessor{
  19.     // steps he in responsibility
  20.  
  21.     LogProcessor nextLogProcessor;
  22.  
  23.     LogProcessor(LogProcessor logger){
  24.         this.nextLogProcessor = logger;
  25.     }
  26.  
  27.     public void log(String logLevel, String message){
  28.         if(nextLogProcessor != null){
  29.             nextLogProcessor.log(logLevel, message);
  30.         }
  31.     }
  32. }
  33.  
  34. class InfoLogProcessor extends LogProcessor{
  35.     InfoLogProcessor(LogProcessor logProcessor){
  36.         // creating next log processor
  37.         super(logProcessor);
  38.     }
  39.  
  40.     public void log(String logLevel, String message){
  41.         if(logLevel == "INFO"){
  42.             System.out.println("INFO:" + message);
  43.         }else{
  44.             super.log(logLevel, message);
  45.         }
  46.     }
  47.  
  48. }
  49.  
  50. class ErrorLogProcessor extends LogProcessor{
  51.     ErrorLogProcessor(LogProcessor logProcessor){
  52.         super(logProcessor);
  53.     }
  54.  
  55.     public void log(String logLevel, String message){
  56.         System.out.println("ERROR:" + message);
  57.     }
  58.  
  59. }
  60.  
  61. public class Main{
  62.     public static void main(String args[]) throws Exception{
  63.         LogProcessor logProcessor = new InfoLogProcessor(new ErrorLogProcessor(null));
  64.         logProcessor.log("INFO", "stops at info logging");
  65.         logProcessor.log("something", "nothing matches");
  66.  
  67.  
  68.         // INFO:stops at info logging
  69.         // ERROR:nothing matches
  70.  
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement