Chain-of-responsibility Pattern
The Chain-of-responsibility pattern lets more than one object handle a request without mutual knowledge. We avoid coupling between the sender of a request and the possible receivers. We place all receivers in a chain which lets the receiving objects pass the request along to the next receiver in the chain until one receiver handles it, or the end of the chain is reached.Where to use
•When more than one object may handle a request, and the handler isn't known.•When you want to issue a request to one of several objects without specifying the receiver explicitly.
•When the set of objects that can handle a request should be specified dynamically.
Benefits
•It reduces coupling.•It increases the flexibility of handling a request.
Drawbacks/consequences
Reception isn't guaranteed since a request has no explicit receiver, there's no guarantee it will be handled unless the chain is configured properly.Chain-of-responsibility Pattern Class Diagram
Chain-of-responsibility Pattern example
In the following source code example the ChainDemo is responsible for creating a chain of Handler instances, and pass 3 requests to them. The Handlers will randomly decide if and when any of them will handle the request.public class Handler { private static java.util.Random s_rn = new java.util.Random(); private static int s_next = 1; private int m_id = s_next++; private Handler m_next; public void add(Handler next) { if (m_next == null) m_next = next; else m_next.add(next); } public void wrap_around(Handler root) { if (m_next == null) m_next = root; else m_next.wrap_around(root); } public void handle(int num) { if (s_rn.nextInt(4) != 0) { System.out.print(m_id + "-busy "); m_next.handle(num); } else System.out.println(m_id + "-handled-" + num); } } public class ChainDemo { public static void main(String[] args) { Handler chain_root = new Handler(); chain_root.add(new Handler()); chain_root.add(new Handler()); chain_root.add(new Handler()); chain_root.wrap_around(chain_root); for (int i = 1; i <= 3; i++) chain_root.handle(i); } }When ChainDemo is executed the result is:
c:>1-busy 2-busy 3-handled-1
c:>1-busy 2-busy 3-busy 4-busy 1-busy 2-busy 3-busy 4-busy 1-
busy 2-handled-2
c:>1-handled-3
0 comments:
Post a Comment