Design Patterns in Java Chapter 12 Chain of Responsibility

Post on 15-Feb-2016

47 views 0 download

Tags:

description

Design Patterns in Java Chapter 12 Chain of Responsibility. Summary prepared by Kirk Scott. One general goal of a good object-oriented design is loose coupling The idea is that changes in one area of the design won’t require changes in other areas - PowerPoint PPT Presentation

Transcript of Design Patterns in Java Chapter 12 Chain of Responsibility

1

Design Patterns in JavaChapter 12

Chain of Responsibility

Summary prepared by Kirk Scott

2

• One general goal of a good object-oriented design is loose coupling

• The idea is that changes in one area of the design won’t require changes in other areas

• Encapsulation in Java provides a certain degree of loose coupling

• Client objects are insulated from changes in class implementation code as long as the set of public methods remains the same

3

• Inheritance, polymorphism, and dynamic binding all in their own way support loose coupling

• Client code doesn’t have to know where in an inheritance hierarchy a method is implemented

• Client code can call methods on superclass references or objects of classes that implement a given interface

4

• On the other hand, you’ve also seen code where it can be useful to call getClass(), for example, to find out what class an object is an instance of

• The use of that method emphasized this simple fact of programming, which was already clear:

• In order to call a method, in general, you need to know what kind of object you are trying to call it on

5

• This reflects a kind of coupling:• The client has to know which class/object it’s

working with• Or viewed another way, the client has to know

which class/object actually has the method containing the functionality it wants to use

6

• This kind of coupling can be loosened in certain kinds of software designs

• For example, the objects in a design may be in some sort of relationship where a call made on one object can be satisfied by a call “through” to another

• In other words, one object will have the method, so that the call can be made on it

• However, the implementation of the method depends on the existence of the functionality in another class that the call is passed to

7

• The book gives a prototypical example of the kind of relationship where calls are passed

• This example is when objects are related in a tree structure

• Calls to one object can be passed “up the tree” until they can be satisfied

8

• Notice that this is a responsibility pattern• You decrease the coupling between the client

and the base objects it uses• In other words, the client can merrily call the

desired method on (potentially many different) objects, not knowing how the functionality is achieved, as usual

9

• However, you offload responsibility from one base object that is called to another which provides the functionality

• This means that there is increased coupling among the base objects in the design

10

• Book definition:• The intent of the Chain of Responsibility

pattern is to avoid coupling the sender of a request to its receiver, by giving more than one object a chance to handle the request.

11

More Preliminary Ideas

• Think about how inheritance works again• A subclass either inherits a method or

overrides it• If it overrides it, it has the ability to buck the

call upwards using super

12

• Now consider the chapter on composites again

• The whole idea there was that a set of objects ended up in a tree-like, or hierarchical relationship

• However, this was not an is-a or is-a-kind-of inheritance relationship

• It was a has-a relationship

13

• Recall that in UML the composition symbol, the diamond, represents a has-a relationship

• Using that terminology, what is under consideration now is a composition relationship

• The Chain of Responsibility design pattern is intended for use in this kind of situation

14

• In the original composite pattern, an instance of the composite class “has an” instance of the component class

• This means that the parent of the has-a relationships knows about its children

• In the scenario under consideration it’s necessary to buck things up the hierarchy

• This will require including a link, or reference, so that a child in a has-a relationship knows who its parent is

15

• One last general remark• Even though the name of the pattern is Chain

of Responsibility, all of the concrete examples will be of the form “Tree of Responsibility”

• …Of course, there is no such thing as a tree of responsibility

16

• Random association comment mode on:• Tree of life?• Chaingang of love?• Web of deceit?

17

• In theory, the internal relationships of a set of classes in a has-a relationships could be of any kind

• As long as there was a discernible logic to the relationships and responsibilities it would be possible to implement some sort of chain of responsibility in the structure

• A linked list or a doubly linked list could have a chain of responsibility, for example

• A call to one object would be bucked to its neighbor until the method returned the desired result

18

An Ordinary Chain of Responsibility

• The authors begin describing the pattern with a concrete example

• In a factory setting, various machines may have specific engineers assigned to them

• A sufficiently important or complicated machine may have its own engineer

• A simpler machine which is part of a composition of machines may have as its engineer the engineer assigned to the composition of machines that it belongs to

19

• From the design pattern point of view, the software goal can be described as follows:

• Suppose client code is trying to find the engineer assigned to a given machine

• It is desirable for the client code only to have to make one call

20

• This is the undesirable scenario:• The client code makes the call• The call returns null, or some other value

indicating lack of success• The client then has to make a call to obtain a

reference to the parent• The client then makes the call on the parent• This could continue an arbitrary number of times,

from parent to grandparent and so on

21

• In other words, you don’t want the client code cluttered up in this way:

• Make call to get engineer of object• If not successful, make call to get parent of object• Make call to get engineer of parent• If not successful, make call to get parent of

parent• …

22

• Suppose that the method for getting the responsible engineer is getResponsible()

• You’d like the composition hierarchy to be structured so that the client code simply has to call getResponsible() an object

• If the object doesn’t have an engineer directly assigned to it, in the implementation of the getResponsible() there is a call to getResponsible() on the object’s parent

23

• Notice that this is reminiscent of recursion • The respective calls to getResponsible() work their

way up a has-a tree until they reach the root• The root case will be considered later• The book’s UML diagram of the composite under

consideration is shown on the next overhead• Note that getResponsible() returns an instance of

the Engineer class

24

25

• Note that the MachineComponent class has a responsible:Engineer instance variable as well as a getResponsible():Engineer method

• There is no requirement that the responsible instance variable not be null

• In the code, if(responsible == null) would be the trigger for calling getResponsible() on the parent object

26

• Challenge 2.1• Point out two weaknesses of the design

shown in Figure 12.1.

27

• Solution 12.1• Some potential disadvantages of the Chain of

Responsibility design that Oozinoz uses for finding a machine’s responsible engineer include the following.

28

• 1. We haven’t specified how the chain will be set up so that machines know their parent.

• In practice, it may be difficult to ensure that parents are never null.

29

• Comment mode on:• Note that this is talking about null parents, not

null responsible engineers. • What they’re saying is related to what happened

with the composite examples: • How do you know that the (tree) structure is set

up correctly? • How do you know you have at least one parent as

well as no more than one parent?

30

• 2. It is conceivable that the search for a parent could enter an infinite loop, depending on how the parents are set up.

• [This is the same situation as in the previous point

• The tree structure could be incorrectly set up and contain a cycle, for example.]

31

• 3. Not all objects have all the behaviors implied by these new methods.

• (For example, the top level item has no parent.)• [This is related to the previous points• How do you know you have a correctly

structured tree?• Also, how do you deal with the fact that the root

node of a tree is special?]

32

• 4. The present design is light on details regarding how the system knows which engineers are currently in the factory and available.

• It’s not clear how “real time” this responsibility needs to be.

• [End of challenge solution.]

33

• The book says the following:• This pattern helps simplify code when it’s not obvious

which object in a group should handle a request.• Stated more accurately, this pattern helps when there

is an internal logic to which object might handle a request

• If there is an internal pattern, using the design pattern might make client code considerably easier to write

34

Refactoring to Chain of Responsibility

• The sign that code might benefit from the chain of responsibility design pattern is when client code makes “probing” calls

• The assumption up to this point has been that every class implements the desired method

• Depending on the situation, it might return null when called on some objects

35

• The book implicitly extends the idea by making this observation:

• To implement the design pattern, make sure that every class in question implements the method—with a chaining strategy for those that can’t return a value

• In other words, null is not just returned in some situations• The book wants to introduce an example where some

kinds of objects can never satisfy a call to getResponsible() without passing the call on to their parents

36

• The book illustrates this extension by adding tools and tool carts to the design scenario

• Tool carts have engineers assigned to them, like machines do

• Individual tools do not have engineers assigned to them

• The engineer assigned to a tool is always the engineer assigned to the cart that the tool belongs to

37

• The book makes this real in a code sense by introducing a VisualizationItem interface

• The elements of a graphical application would have a visual representation

• These visual elements might include machine composites, tool carts, and tools

• The UML diagram on the following overhead shows the scenario

38

39

• This UML diagram is for an un-refactored design

• MachineComponent, ToolCart, and Tool all implement the VisualizationItem interface

• However, there is no getResponsible() method declared in the VisualizationItem interface

• That means that not all of the implementing classes have that method

40

• In particular, MachineComponent and ToolCart have the getResponsible() method

• Machine and MachineComposite have it by inheritance

• The Tool class doesn’t have that method• In client code, it will be necessary to check

which kind of object you’re working with before calling getResponsible()

41

• On the overhead following the next one, code is shown for AmbitiousMenu

• It contains a series of if statements where it is calling getResponsible() on various kinds of visualization objects, like machines and tools

• The series of if statements is “probing” code• This suggests that refactoring would help

42

• It is not so much that AmbitiousMenu should be rewritten

• It’s that the machine/tool code should be rewritten

• If this is done according to the Chain of Responsibility design pattern, the code for AmbitiousMenu will be greatly simplified

• The code of AmbitiousMenu is shown on the next overhead

43

• public class AmbitiousMenu • {• public Engineer getResponsible(VisualizationItem item) • {• if (item instanceof Tool)• {• Tool t = (Tool) item;• return t.getToolCart().getResponsible();• }• if (item instanceof ToolCart) • {• ToolCart tc = (ToolCart) item;• return tc.getResponsible();• }

44

• if (item instanceof MachineComponent) • {• MachineComponent c = (MachineComponent) item;• if (c.getResponsible() != null) • return c.getResponsible();

• if (c.getParent() != null) • return c.getParent().getResponsible();• }• return null;• }• }

45

• In this example it is the menu that would be the caller or client of the various machine, cart, and tool classes

• Clearly this is not a complete example but it includes everything necessary in order to illustrate the idea

• It is not critical to the example that the method under consideration in the AmbitiousMenu is also called getResponsible()

• What is important is the contortions that this method has to go through in order to call getResponsible() on VisualizationItem objects

46

• Challenge 12.2• Redraw the diagram in Figure 12.2, moving

the getResponsible() method to VisualizationItem and adding this behavior to Tool.

47

• Comment mode on:• Note that this is a mindlessly easy challenge• The point is that they’re telling you that the solution

to the problem is to have all classes that implement the interface have a getResponsible() method

• Then the only thing that remains is the question of implementation code

• Figure 12.2 is shown again on the following overhead

48

49

• Solution 12.2• Your diagram should look similar to Figure

B.15.

50

51

• Comment mode on:• Actually, the book answer is deceptively

simple.• It shows the interface, Tool, ToolCart, and

MachineComponent with a getResponsible() method

• It happens to eliminate the Machine and MachineComposite classes from the diagram

52

• Comment mode continued:• Even though those classes don’t appear in this

solution diagram, they’re still part of the design• They already have the getResponsble() method in

them and they don’t have to be shown again• As subclasses of MachineComponent they either

inherit or override the getResponsible() method

53

• The (beneficial) results of the design change reflected in the new UML diagram:

• The menu code becomes much simpler as a result of this design change

• The implementation of the getResponsible() method in each class is also easy

• The menu code is given on the next overhead

54

• public class AmbitiousMenu2• {• public Engineer getResponsible(VisualizationItem item)• {• return item.getResponsible();• }• }

55

• Challenge 12.3• Write the code for the getResponsible()

method for:• A. MachineComponent• B. Tool• C. ToolCart

56

• Solution 12.3• A. A MachineComponent object may have an

explicitly assigned responsible person.• If it doesn’t, it passes the request to its parent.• [The code is shown on the next overhead.]

57

• public Engineer getResponsible()• {• if(responsible != null)• return responsible;• if(parent != null)• return parent.getResponsible();• return null;• }

58

• B. The code for Tool.Responsible reflects the statement that “tools are always assigned to tool carts”:

• public Engineer getResponsible()• {• return toolCart.getResponsible();• }

59

• C. The ToolCart code reflects the statement that “tool carts have a responsible engineer”:

• public Engineer getResponsible()• {• return responsible;• }

60

Anchoring a Chain

• The getResponsible() code for MachineComponent had an if statement to handle the case of a null parent

• A parent instance variable exists in this class and has been shown in the UML diagrams

• However, no code has been given so far that gave objects parents

• Likewise, no code has been given that required objects to have parents

61

• Construction time would be a good time to specify an object’s parent

• If parents can’t be null, it might also be helpful to throw an exception if that requirement isn’t met

• The idea of a constructor throwing an exception was discussed as a side note in Chapter 8 on the Singleton design pattern

• You also have to deal with the special case of the root node, which doesn’t have a parent

62

• The book suggests that a special class, MachineRoot, be created as a subclass of MachineComposite

• It states that MachineRoot should not be a subclass of MachineComponent

• As far as I can tell, it would be possible to make that alternative work, but it is slightly less logical

63

• Clearly, the root couldn’t be a simple machine• MachineComponent is also not a good choice

because, by definition, a MachineComponent could be either a Machine or a MachineComposite

• The most logical choice for MachineRoot is a kind of MachineComposite, since the root by definition would have to be a composite

64

• The book then states that a MachineComponent will always have a responsible engineer if the following three requirements are met in setting up the code:

• 1. The constructor(s) for MachineRoot require an Engineer object.

65

• 2. The constructor(s) for MachineComponent require a parent object that is itself a MachineComponent.

• Comment mode on:• Logically you might think that parents ought to be

composites instead of components• However, the superclass MachineComponent doesn’t

“know” its subclass MachineComposite• Therefore, if you are going to define parenthood in the

component class, then a parent has to be of the type component

66

• 3. Only MachineRoot uses null as the value for its parent.• Comment mode on:• This is what in database would be called an integrity

constraint• In other words, you could always pass in null as the value

for a parent when constructing• You should only do so for the root• Alternatively, you could set up an exception throwing

mechanism to disallow certain parameter values on construction

67

• Challenge 12.4• Fill in the constructors in Figure 12.3 to

support a design that ensures that every MachineComponent object has a responsible engineer.

68

69

• Solution 12.4• Your solution should look something like Figure

B.16.• Your constructors should allow Machine and

MachineComposite objects to be instantiated with or without an assigned engineer.

• Whenever a MachineComponent object does not have an assigned engineer, it can get a responsible engineer from its parent.

70

71

• Anchoring a chain of responsibility improves the way the object-oriented design models reality

• It also simplifies the code• The getResponsible() method of the

MachineComponent class can be implemented as shown on the following overhead

72

• public Engineer getResponsible()• {• if(responsible != null)• return responsible;• return parent.getResponsible();• }

73

Chain of Responsibility without Composite

• Fundamentally, the Chain of Responsibility design pattern relies on a structure in the problem domain

• That structure provides an order for searching for the object responsible for providing some service

• It was convenient to illustrate the idea using composition, which arose as an earlier pattern

• However, the chain of responsibility doesn’t have to be based on composition (a tree-like structure)

74

• Challenge 12.5• Cite an example in which the Chain of

Responsibility pattern might occur where the chained objects do not form a composite.

75

• Solution 12.5• Chain of Responsibility might apply to objects that do not

form a composite when• 1. A chain of on-call engineers follows a standard rotation.• If the primary on-call engineer does not answer a

production support page in a specific amount of time, the notification system pages the next engineer in the chain.

• 2. Users enter information, such as the date of an event; a chain of parsers can take turns trying to decode the user’s text.

76

Summary

• The Chain of Responsibility pattern relieves a client from having to know which objects in a collection support which behavior

• Note that in order to support this, concretely every object in a collection has a method of the desired name

• Some of the objects may pass a call to the method to another object in the collection

77

• This decouples the client from the objects• It also means that the objects are now more

tightly coupled, since they pass requests on to other objects in the collection

78

• The main example given of a chain of responsibility was behavior in a composition

• In other words, there’s a containment hierarchy where calls can be bucked up the hierarchy

• The book also mentions parsing as an application domain, but without an example or much clear explanation

79

• When applied in an appropriate problem domain, the Chain of Responsibility design pattern can accomplish the following:

• Simpler code in the client• Also, simple code in the collection of objects

which neatly passes around calls in a manner reflecting the underlying structure of the containment hierarchy (or other problem domain)

80

The End