SlideShare uma empresa Scribd logo
1 de 15
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

Design Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityDesign Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityMudasir Qazi
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Androidma-polimi
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
Behavioral Design Patterns
Behavioral Design PatternsBehavioral Design Patterns
Behavioral Design PatternsLidan Hifi
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
REQUIREMENT ENGINEERING
REQUIREMENT ENGINEERINGREQUIREMENT ENGINEERING
REQUIREMENT ENGINEERINGSaqib Raza
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering conceptsKomal Singh
 
Software Engineering :UML class diagrams
Software Engineering :UML class diagramsSoftware Engineering :UML class diagrams
Software Engineering :UML class diagramsAjit Nayak
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling sharqiyem
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patternsLilia Sfaxi
 

Mais procurados (20)

Design Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityDesign Pattern - Chain of Responsibility
Design Pattern - Chain of Responsibility
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Android
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Decorator design pattern
Decorator design patternDecorator design pattern
Decorator design pattern
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Design pattern
Design patternDesign pattern
Design pattern
 
Behavioral Design Patterns
Behavioral Design PatternsBehavioral Design Patterns
Behavioral Design Patterns
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
REQUIREMENT ENGINEERING
REQUIREMENT ENGINEERINGREQUIREMENT ENGINEERING
REQUIREMENT ENGINEERING
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering concepts
 
Software Engineering :UML class diagrams
Software Engineering :UML class diagramsSoftware Engineering :UML class diagrams
Software Engineering :UML class diagrams
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
React Hooks
React HooksReact Hooks
React Hooks
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 

Semelhante a Chain of responsibility

Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
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 .pdfPranavAnil9
 
Net practicals lab mannual
Net practicals lab mannualNet practicals lab mannual
Net practicals lab mannualAbhishek Pathak
 
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 trAbramMartino96
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShakir 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 & STMMario Fusco
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best PracticesLluis Franco
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversionsKnoldus Inc.
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
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.pptDeepVala5
 
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 ReferenceSeung-Bum Lee
 

Semelhante a 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