Chain of Responsibility
and
Composite
CSCI 3132 Summer 2011
1
Mo#va#on • Consider a context-‐sensi#ve help system for a GUIDE • The object that ul#mately provides the help isn't known explicitly to the object (e.g., a buHon) that ini#ates the help request. • So use a chain of objects to decouple the senders from the receivers. • The request gets passed along the chain un#l one of the objects handles it. • Each object on the chain shares a common interface for handling requests and for accessing its successor on the chain 2
Chain of Responsibility PaHern • Intent – Avoid coupling sender of request to its receiver by giving more than one object chance to handle request. Chain receiving objects and pass request along un#l an object handles it. 3
Example 2 4
Applicability • Use Chain of responsibility paHern when – more than one object may handle a request, and the handler isn’t known a priori. – you want to issue a request to one of several objects without specifying the receiver explicitly – the set of objects that can handle a request should be specified dynamically 5
Chain of Responsibility Structure Avoid coupling the sender of a request to its receiver by giving more
than one object a chance to handle the request
6
Chain of responsibility -‐ Par#cipants • Handler (HelpHandler) – defines an interface for handling requests – (op#onal) implements the successor link • ConcreteHandler (PrintBuHon, PrintDialog) – handles requests it is responsible for – can access its successor – if the ConcreteHandler can handle the request, is does so; otherwise it forwards the request to its successor • Client – ini#ates the request to a ConcreteHandler object on the chain 7
Chain of responsibility Consequences • Reduced coupling – The paHern frees an object from knowing other object handles a request • Added flexibility in assigning responsibili#es to objects – changing the chain in run-‐#me – use sub-‐classing to specify handlers sta#cally • Receipt isn’t guaranteed 8
Chain of responsibility Implementa#on • Implemen#ng the successor chain – define a new links (in Handler usually), or – use existent links (for example, child-‐parent links). • Connec#ng successors class HelpHandler { public:
HelpHandler(HelpHandler* s) : _successor(s) {}
virtual void HandleHelp();
private:
HelpHandler* _successor;
};
void HelpHandler::HandleHelp() {
if (_successor)
_successor->HandleHelp();
}
9
Chain of responsibility Implementa#on • Represen#ng requests – The simplest form: the request is a hard-‐coded opera#on invoca#on • you can forward only the fixed set of requests – An alterna#ve: use a single handler func#on which takes a request object as parameter void Handler::HandleRequest(Request* theRequest) {
switch (theRequest->getKind()) {
case Help:
HandleHelp((HelpRequest*)theRequest);
break;
…
}
10
Behavioral PaHern Summary • Behavioral paHerns are concerned with the assignment of responsibili#es between objects, or, encapsula#ng behavior in an object and delega#ng requests to it. • Chain of responsibility, Command, and Observer, address how you can decouple senders and receivers, but with different trade-‐offs. – Chain of responsibility passes a sender request along a chain of poten#al receivers. – Command normally specifies a sender-‐receiver connec#on with a subclass. – Observer defines a very decoupled interface that allows for mul#ple receivers to be configured at run-‐#me. 11
Structural PaHerns • Concerned with how classes and objects are combined to create larger structures. • Concerned with composing objects to establish new func#onality. 12
Composite PaHern • A composite is a group of objects in which some objects
contain others; one object may represent groups, and
another may represent an individual item, a leaf.
• Facilitates the composition of objects into a stree structure,
a hierarchy, that represent part-whole hierarchies.
• These hierarchies consist of both primitive and composite
objects.
• The operations are appropriate for processing and
traversing trees.
13
Example • Example: complex graphic applica#on, with hierarchically nested objects. • Main idea: Containers and leaf objects appear the same to clients. • Up and down delega6on: – A container may delegate to all contained objects. – A leaf/container may delegate to containing objects. aComposite aLeaf aLeaf aComposite aLeaf aLeaf aLeaf 14
Graphic Draw() Add(Graphic) Remove(Graphic) GetChild(int) graphics Line Draw( ) Rectangle Draw( ) Text Draw( ) Picture Draw( ) Add(Graphic g) Remove(Graphic) GetChild(int) forall g in graphics g.Draw() add g to list of graphics 15
Par#cipants • Component (Graphic) – declares interface for objects in the composi#on – implements default behavior – declares an interface for accessing and managing its child components – (op#onal) declares an interface for accessing a component’s parent • Leaf (Rectangle, Line, Text etc.) – defines behavior for primi#ve objects in the composi#on • Composite (Picture) – defines behavior for components having children – stores child components – implements child-‐related opera#ons in the Component interface • Client – manipulates objects in the composi#on through the Component interface 16
Composite paHern -‐ implementa#on • Explicit parent references – define the parent reference in the Component class – essen#al to maintain the invariant that all children of a composite have as their parent the composite that in turn has them as children – easiest way to ensure -‐ change the component’s parent only when it’s being added or removed from composite • Sharing components – mul#ple parents – ambigui#es as a request propagates up the structure 17
Composite PaHern Class Diagram Component
Client
*
operation()
Leaf
operation()
Composite
operation()
other()
Each node of the Component structure can respond to some common
operation(s). I.e. the client can send the common operation to Component
and the structure responds “appropriately”.
18
Example MenuComponent
add()
remove()
getChild()
print()…
Waitress
MenuItem
print()
*
Menu
add()
remove()
getChild()
print()…
19
Composite PaHern Menu
menuComponents: ArrayList
add()
remove()
getChild()
print()…
Note the association from Menu to MenuComponents
with an array list data type.
How to implementation of print() in Menu and in
MenuItem
20
Composite PaHern In the Menu class we have a print() that is appropriate for
an internal node.
public void print() {
System.out.print("\n" + getName());
System.out.println(", " + getDescription());
System.out.println("---------------------");
}
}
Iterator iterator = menuComponents.iterator();
while (iterator.hasNext()) {
MenuComponent menuComponent =
(MenuComponent)iterator.next();
menuComponent.print();
21
Composite PaHern In the MenuItem class we have a print() that is appropriate
for a leaf:
public void print() {
System.out.print(" " + getName());
if (isVegetarian()) {
System.out.print("(v)");
}
System.out.println(", " + getPrice());
System.out.println("
-- " + getDescription());
}
22
Summary • The Composite PaHern is used to represent part-‐
whole object hierarchies. • Clients interact with objects through the component class. • It enables clients to to ignore the specifics of which leaf or composite class they use. • Can be used recursively, so that Display can show both flares and stars. • New components can easily be added to a design. 23
© Copyright 2026 Paperzz