SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Alphorm.com Formation Big Data avec Apache Spark: Initiation
Alphorm.com Formation Big Data avec Apache Spark: InitiationAlphorm.com Formation Big Data avec Apache Spark: Initiation
Alphorm.com Formation Big Data avec Apache Spark: Initiation
Alphorm
 

Was ist angesagt? (20)

Command Design Pattern
Command Design Pattern Command Design Pattern
Command Design Pattern
 
Les Streams de Java 8
Les Streams de Java 8Les Streams de Java 8
Les Streams de Java 8
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Abstract Factory Pattern (Example & Implementation in Java)
Abstract Factory Pattern (Example & Implementation in Java)Abstract Factory Pattern (Example & Implementation in Java)
Abstract Factory Pattern (Example & Implementation in Java)
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Flyweight Pattern
Flyweight PatternFlyweight Pattern
Flyweight Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
POO Java Chapitre 4 Heritage et Polymorphisme
POO Java Chapitre 4 Heritage et PolymorphismePOO Java Chapitre 4 Heritage et Polymorphisme
POO Java Chapitre 4 Heritage et Polymorphisme
 
Alphorm.com Formation Big Data avec Apache Spark: Initiation
Alphorm.com Formation Big Data avec Apache Spark: InitiationAlphorm.com Formation Big Data avec Apache Spark: Initiation
Alphorm.com Formation Big Data avec Apache Spark: Initiation
 
Java CRUD Mechanism with SQL Server Database
Java CRUD Mechanism with SQL Server DatabaseJava CRUD Mechanism with SQL Server Database
Java CRUD Mechanism with SQL Server Database
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
 

Ähnlich wie 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
 

Ähnlich wie 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