Intention: give multiple objects the opportunity to process requests, so as to avoid coupling between the request sender and receiver. connect these objects into a chain and pass requests along the chain until an object processes it.
Applicability:
Multiple objects can process one request, which is automatically determined when processing the request
You want to submit a request to one of multiple objects without specifying the recipient.
The object set that can process a request should be dynamically specified
Example:
ExampleCode:
Class Chandler
{
Public:
Chandler (Chandler *
Nexthandler );
Public:
~ Chandler (void );
Public:
Void
Handlerequest (crequest req)
{
If (ismatch (req. getrequesttype ()))
{
_ Handlerequest (req );
}
Else
{
If (m_nexthandler)
{
M_nexthandler-> handlerequest (req );
}
Else
{
_ Tprintf (_ T ("unhandler
Message/N "));
}
}
}
Protected:
Virtual void _ handlerequest (crequest req) = 0;
Virtual bool ismatch (crequest: requesttype reqtype) = 0;
PRIVATE:
Chandler * m_nexthandler;
};
// Message Processing
Class cmessagehandler: Public Chandler
{
Public:
Cmessagehandler (Chandler * pnexthandler)
: Chandler (pnexthandler)
{
}
Public:
~ Cmessagehandler ()
{
}
Public:
Virtual bool ismatch (crequest: requesttype
Reqtype)
{
If (reqtype = crequest: emessage)
{
Return true;
}
Return false;
}
Virtual void _ handlerequest (crequest req)
{
_ Tprintf (_ T ("message handled/N "));
}
};
// Keyboard processing class processes keyboard messages
Class ckeyhandler: Public
Cmessagehandler
{
Public:
Ckeyhandler (Chandler *
Pnexthandler)
: Cmessagehandler (pnexthandler)
{
}
Public:
~ Ckeyhandler ()
{
}
Public:
Virtual bool ismatch (crequest: requesttype reqtype)
{
If (reqtype = crequest: EKEY)
{
Return
True;
}
Return false;
}
Virtual void
_ Handlerequest (crequest req)
{
_ Tprintf (_ T ("key message
Handled/N "));
}
};
// Process the request
Class crequest
{
Public:
Enum requesttype
{
Emessage,
EKEY,
Emouse,
};
Public:
Crequest (crequest: requesttype reqtype );
Public:
~ Crequest (void );
Public:
Crequest: requesttype
Getrequesttype ()
{
Return m_reqtype;
}
PRIVATE:
Crequest: requesttype m_reqtype;
};
// Call
Ckeyhandler keyhandler (null );
Cmessagehandler
Messagehandler (& keyhandler );
Crequest keyreq (crequest: EKEY );
Crequest msgreq (crequest: emessage );
Crequest
Mousereq (crequest: emouse );
Messagehandler. handlerequest (keyreq );
Messagehandler. handlerequest (msgreq );
Messagehandler. handlerequest (mousereq );
Result