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?

Cassandra & puppet, scaling data at $15 per month
Cassandra & puppet, scaling data at $15 per monthCassandra & puppet, scaling data at $15 per month
Cassandra & puppet, scaling data at $15 per monthdaveconnors
 
A really really fast introduction to PySpark - lightning fast cluster computi...
A really really fast introduction to PySpark - lightning fast cluster computi...A really really fast introduction to PySpark - lightning fast cluster computi...
A really really fast introduction to PySpark - lightning fast cluster computi...Holden Karau
 
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteAdvanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteStreamNative
 
Apache kafka 확장과 응용
Apache kafka 확장과 응용Apache kafka 확장과 응용
Apache kafka 확장과 응용JANGWONSEO4
 
Resilience4j with Spring Boot
Resilience4j with Spring BootResilience4j with Spring Boot
Resilience4j with Spring BootKnoldus Inc.
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
Redis + Apache Spark = Swiss Army Knife Meets Kitchen Sink
Redis + Apache Spark = Swiss Army Knife Meets Kitchen SinkRedis + Apache Spark = Swiss Army Knife Meets Kitchen Sink
Redis + Apache Spark = Swiss Army Knife Meets Kitchen SinkDatabricks
 
How to Implement Domain Driven Design in Real Life SDLC
How to Implement Domain Driven Design  in Real Life SDLCHow to Implement Domain Driven Design  in Real Life SDLC
How to Implement Domain Driven Design in Real Life SDLCAbdul Karim
 
Presto At Arm Treasure Data - 2019 Updates
Presto At Arm Treasure Data - 2019 UpdatesPresto At Arm Treasure Data - 2019 Updates
Presto At Arm Treasure Data - 2019 UpdatesTaro L. Saito
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APISvetlin Nakov
 
High Concurrency Architecture at TIKI
High Concurrency Architecture at TIKIHigh Concurrency Architecture at TIKI
High Concurrency Architecture at TIKINghia Minh
 
Cassandra at eBay - Cassandra Summit 2012
Cassandra at eBay - Cassandra Summit 2012Cassandra at eBay - Cassandra Summit 2012
Cassandra at eBay - Cassandra Summit 2012Jay Patel
 
Basis path testing
Basis path testingBasis path testing
Basis path testingHoa Le
 
Big data analytics with Spark & Cassandra
Big data analytics with Spark & Cassandra Big data analytics with Spark & Cassandra
Big data analytics with Spark & Cassandra Matthias Niehoff
 
Introduction to the Disruptor
Introduction to the DisruptorIntroduction to the Disruptor
Introduction to the DisruptorTrisha Gee
 

Was ist angesagt? (20)

Composite pattern
Composite patternComposite pattern
Composite pattern
 
Cassandra & puppet, scaling data at $15 per month
Cassandra & puppet, scaling data at $15 per monthCassandra & puppet, scaling data at $15 per month
Cassandra & puppet, scaling data at $15 per month
 
A really really fast introduction to PySpark - lightning fast cluster computi...
A really really fast introduction to PySpark - lightning fast cluster computi...A really really fast introduction to PySpark - lightning fast cluster computi...
A really really fast introduction to PySpark - lightning fast cluster computi...
 
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteAdvanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
 
Apache kafka 확장과 응용
Apache kafka 확장과 응용Apache kafka 확장과 응용
Apache kafka 확장과 응용
 
Caching
CachingCaching
Caching
 
Resilience4j with Spring Boot
Resilience4j with Spring BootResilience4j with Spring Boot
Resilience4j with Spring Boot
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Redis + Apache Spark = Swiss Army Knife Meets Kitchen Sink
Redis + Apache Spark = Swiss Army Knife Meets Kitchen SinkRedis + Apache Spark = Swiss Army Knife Meets Kitchen Sink
Redis + Apache Spark = Swiss Army Knife Meets Kitchen Sink
 
How to Implement Domain Driven Design in Real Life SDLC
How to Implement Domain Driven Design  in Real Life SDLCHow to Implement Domain Driven Design  in Real Life SDLC
How to Implement Domain Driven Design in Real Life SDLC
 
Presto At Arm Treasure Data - 2019 Updates
Presto At Arm Treasure Data - 2019 UpdatesPresto At Arm Treasure Data - 2019 Updates
Presto At Arm Treasure Data - 2019 Updates
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
 
Uml sequence diagrams
Uml sequence diagramsUml sequence diagrams
Uml sequence diagrams
 
High Concurrency Architecture at TIKI
High Concurrency Architecture at TIKIHigh Concurrency Architecture at TIKI
High Concurrency Architecture at TIKI
 
Mediator Design Pattern
Mediator Design PatternMediator Design Pattern
Mediator Design Pattern
 
Cassandra at eBay - Cassandra Summit 2012
Cassandra at eBay - Cassandra Summit 2012Cassandra at eBay - Cassandra Summit 2012
Cassandra at eBay - Cassandra Summit 2012
 
Basis path testing
Basis path testingBasis path testing
Basis path testing
 
Big data analytics with Spark & Cassandra
Big data analytics with Spark & Cassandra Big data analytics with Spark & Cassandra
Big data analytics with Spark & Cassandra
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Introduction to the Disruptor
Introduction to the DisruptorIntroduction to the Disruptor
Introduction to the Disruptor
 

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

Ä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