Now that the product and the chain links exist, the client needs only to weave the links together to make a chain and pass a product to its first link.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classClient{
Client() {
ILink linkA = new LinkA();
ILink linkB = new LinkB();
ILink linkC = new LinkC();
/* creating a chain by introducing
* the next link of each link.
*/
linkA.setNextLink(linkB);
linkB.setNextLink(linkC);
linkA.process(new Product());
}
}
Important Benefits
This pattern decouples commands/handlers (e.g ‘Link’) and allows them to have their own independent logic.
Example
Suppose that you’re developing a module for the local post office to send out notifications to recipients when they receive a package. This notification message shall be sent by mail, sms and email. Accordingly our Message object could be designed as follows.
1
2
3
4
5
6
classMessage{
String notificationContent;
String recipientPhone;
String recipientMail;
String recipientAddress;
}
The chain’s ‘Link’ interface is called ‘INotification’ and each implementation contains logic to send a message in a specific way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
interfaceINotification{
voidsetNext(INotification n);
voidsend(Message message);
}
classSmsimplementsINotification{
INotification next;
publicvoidsetNext(INotification n){ next = n; }
publicvoidsend(Message message){
/* send a SMS message to the given number */
if (next != null) next.send(message);
}
}
classEmailimplementsINotification{
INotification next;
publicvoidsetNext(INotification n){ next = n; }
publicvoidsend(Message message){
/* send an email to the given mail address */
if (next != null) next.send(message);
}
}
classPostimplementsINotification{
INotification next;
publicvoidsetNext(INotification n){ next = n; }
publicvoidsend(Message message){
/* print & mail to the given postal address */
if (next != null) next.send(message);
}
}
The client instantiates and links the notifiers to create a chain and finally passes the message to the first link of the chain.