SlideShare a Scribd company logo
1 of 15
Download to read offline
Team 13
Introduction
                  
 Behavioral design pattern.
 Uses a chain of objects to handle a request.
 Objects in the chain forward the request along the
  chain until one of the objects handles the request.
 Avoid coupling the sender of a request to its receiver
  by giving more than one object a chance to handle
  the request.
Class Diagram
                                               successor
client                         Handler
            Request


                             handleRequest()




          ConcreteHandler1       ConcreteHandler2




          handleRequest()         handleRequest()
Usage
                      
 Several objects have similar methods that could be
  appropriate for the action that the program is
  requesting.



 One of the objects might be most suitable.
Usage (cont.…)
                
 Having new objects that want to add to the list of
  processing options while the program execution.



 When more than one object may handle a request
  and the actual handler is not know in advance
Implementation
                  
In brief,

 We create four objects that can either “Add”,
  “Subtract”, “Multiply” or “Divide”.

 Send two numbers and a command, that allow above
  four objects to decide which can handle the
  requested calculation.
Implementation
               
 Interface

  public interface Chain
      {
           void calculate(Numbers request);
           void setChain(Chain nextChain);
      }
  }
Implementation
 Numbers Class
                
public class Numbers {

        private int _number1, _number2;
        private string _command;

        public Numbers(int number1, int number2, string command)
        {
            _number1 = number1;
            _number2 = number2;
            _command = command;
        }

        public int getNumber1() { return _number1; }
        public int getNumber2() { return _number2; }
        public string getCommand() { return _command; }
    }
}
Implementation
 Addition Class
                 
Public Addition : Chain {

      private Chain _nextChain;

      public void calculate(Numbers request){

      if (request.getCommand() == "add"){

       Console.WriteLine(“Result: {0}",request.getNumber1()+request.getNumber2());

       }else{ _nextChain.calculate(request);}

       }

       public void setChain(Chain nextChain){
           _nextChain = nextChain;
       }
  }
Implementation
 Subtraction Class
                    
Public Subtraction : Chain {

       private Chain _nextChain;

       public void calculate(Numbers request){

       if (request.getCommand() == "sub"){

        Console.WriteLine(“Result: {0}",request.getNumber1()-request.getNumber2());

        }else{ _nextChain.calculate(request);}

        }

        public void setChain(Chain nextChain){
            _nextChain = nextChain;
        }
   }
Implementation
 Multiplication Class
                       
Public Multiplication : Chain {

       private Chain _nextChain;

       public void calculate(Numbers request){

       if (request.getCommand() == "mul"){

        Console.WriteLine(“Result: {0}",request.getNumber1()*request.getNumber2());

        }else{ _nextChain.calculate(request);}

        }

        public void setChain(Chain nextChain){
            _nextChain = nextChain;
        }
   }
Implementation
 Division Class
                 
Public Division : Chain {

       private Chain _nextChain;

       public void calculate(Numbers request){

       if (request.getCommand() == "div"){

        Console.WriteLine(“Result: {0}",request.getNumber1()/request.getNumber2());

        }else{ “Unidentified Command! Please Check again...”}

        }

        public void setChain(Chain nextChain){
            _nextChain = nextChain;
        }
   }
Implementation
 Demo Class 
class Demo{
        public static void Main()
        {
            Chain chainCalc1 = new   Addition();
            Chain chainCalc2 = new   Subtraction();
            Chain chainCalc3 = new   Multiplication();
            Chain chainCalc4 = new   Division();

           chainCalc1.setChain(chainCalc2);
           chainCalc2.setChain(chainCalc3);
           chainCalc3.setChain(chainCalc4);

           Numbers request1 = new Numbers(10,5,"add");
           Numbers request2 = new Numbers(10,5,"mul");
           chainCalc1.calculate(request1);
           chainCalc1.calculate(request2);

           Console.ReadLine();
       }
Pros & Cons
                   
 Pros
      More efficient
      More flexible
      Refactor and change the code is easy

 Cons
     Handling isn't guaranteed
Chain of responsibility

More Related Content

What's hot

Design Patterns
Design PatternsDesign Patterns
Design Patterns
soms_1
 
Android life cycle
Android life cycleAndroid life cycle
Android life cycle
瑋琮 林
 

What's hot (20)

Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
Java RMI
Java RMIJava RMI
Java RMI
 
Modificateurs d'accès en java
Modificateurs d'accès en javaModificateurs d'accès en java
Modificateurs d'accès en java
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Use Case Diagram
Use Case DiagramUse Case Diagram
Use Case Diagram
 
Appels de procédures distants (RPC)
Appels de procédures distants (RPC)Appels de procédures distants (RPC)
Appels de procédures distants (RPC)
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
JNDI
JNDIJNDI
JNDI
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
String Handling
String HandlingString Handling
String Handling
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor Pattern
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Android life cycle
Android life cycleAndroid life cycle
Android life cycle
 
Single server queue (Simulation Project)
Single server queue (Simulation Project)Single server queue (Simulation Project)
Single server queue (Simulation Project)
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Builder design pattern
Builder design patternBuilder design pattern
Builder design pattern
 
Chp6 - De UML vers C++
Chp6 - De UML vers C++Chp6 - De UML vers C++
Chp6 - De UML vers C++
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 

Similar to Chain of responsibility

Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
Mcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trMcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search tr
AbramMartino96
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
Shakir Majeed Khan
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
Mohammad Shaker
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 

Similar to Chain of responsibility (20)

Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfComputer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
 
Net practicals lab mannual
Net practicals lab mannualNet practicals lab mannual
Net practicals lab mannual
 
Mcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trMcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search tr
 
Java 8 monads
Java 8   monadsJava 8   monads
Java 8 monads
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
 
Thread
ThreadThread
Thread
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversions
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 

Chain of responsibility

  • 2. Introduction   Behavioral design pattern.  Uses a chain of objects to handle a request.  Objects in the chain forward the request along the chain until one of the objects handles the request.  Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.
  • 3. Class Diagram  successor client Handler Request handleRequest() ConcreteHandler1 ConcreteHandler2 handleRequest() handleRequest()
  • 4. Usage   Several objects have similar methods that could be appropriate for the action that the program is requesting.  One of the objects might be most suitable.
  • 5. Usage (cont.…)   Having new objects that want to add to the list of processing options while the program execution.  When more than one object may handle a request and the actual handler is not know in advance
  • 6. Implementation  In brief,  We create four objects that can either “Add”, “Subtract”, “Multiply” or “Divide”.  Send two numbers and a command, that allow above four objects to decide which can handle the requested calculation.
  • 7. Implementation   Interface public interface Chain { void calculate(Numbers request); void setChain(Chain nextChain); } }
  • 8. Implementation  Numbers Class  public class Numbers { private int _number1, _number2; private string _command; public Numbers(int number1, int number2, string command) { _number1 = number1; _number2 = number2; _command = command; } public int getNumber1() { return _number1; } public int getNumber2() { return _number2; } public string getCommand() { return _command; } } }
  • 9. Implementation  Addition Class  Public Addition : Chain { private Chain _nextChain; public void calculate(Numbers request){ if (request.getCommand() == "add"){ Console.WriteLine(“Result: {0}",request.getNumber1()+request.getNumber2()); }else{ _nextChain.calculate(request);} } public void setChain(Chain nextChain){ _nextChain = nextChain; } }
  • 10. Implementation  Subtraction Class  Public Subtraction : Chain { private Chain _nextChain; public void calculate(Numbers request){ if (request.getCommand() == "sub"){ Console.WriteLine(“Result: {0}",request.getNumber1()-request.getNumber2()); }else{ _nextChain.calculate(request);} } public void setChain(Chain nextChain){ _nextChain = nextChain; } }
  • 11. Implementation  Multiplication Class  Public Multiplication : Chain { private Chain _nextChain; public void calculate(Numbers request){ if (request.getCommand() == "mul"){ Console.WriteLine(“Result: {0}",request.getNumber1()*request.getNumber2()); }else{ _nextChain.calculate(request);} } public void setChain(Chain nextChain){ _nextChain = nextChain; } }
  • 12. Implementation  Division Class  Public Division : Chain { private Chain _nextChain; public void calculate(Numbers request){ if (request.getCommand() == "div"){ Console.WriteLine(“Result: {0}",request.getNumber1()/request.getNumber2()); }else{ “Unidentified Command! Please Check again...”} } public void setChain(Chain nextChain){ _nextChain = nextChain; } }
  • 13. Implementation  Demo Class  class Demo{ public static void Main() { Chain chainCalc1 = new Addition(); Chain chainCalc2 = new Subtraction(); Chain chainCalc3 = new Multiplication(); Chain chainCalc4 = new Division(); chainCalc1.setChain(chainCalc2); chainCalc2.setChain(chainCalc3); chainCalc3.setChain(chainCalc4); Numbers request1 = new Numbers(10,5,"add"); Numbers request2 = new Numbers(10,5,"mul"); chainCalc1.calculate(request1); chainCalc1.calculate(request2); Console.ReadLine(); }
  • 14. Pros & Cons   Pros More efficient More flexible Refactor and change the code is easy  Cons Handling isn't guaranteed