Datasheet

DESIGN PATTERNS IN WEB FRAMEWORKS
x
25
So, how do you create such Chain of Responsibility? The main idea of this pattern is to process a
request by a list of consecutive handlers to avoid any hard-wired mappings. The initial client holds
a reference only to the fi rst element in the chain of handlers. Then each handler holds a reference
to the handler afterward. The last handler must always accept the request to avoid passing it to a
NULL value.
A good class structure supporting this behavioral pattern is shown in Figure 1-24. It consists of a
parent
Handler class that calls the handle() method to delegate the request to the next concrete
handler
nextHandler. This Handler class is subclassed by concrete handlers that try to do some-
thing with the request; if they fail, they call the
handle() method of their superclass.
+handle()
nextHandler.handle();
- nextHandler
Handler
+handle()
HandlerTwoHandlerOne
FIGURE 124: Chain of Responsibility pattern structure
Chain of Responsibility is commonly used for fi lters. One example of fi ltering is when a user request
is being processed. First it checks whether the given controller exists or not. If it doesn’t exist, a 404
error is displayed. If it does exist, the request is passed to the controller, which handles it further.
It checks whether a user tries to access an unsecured page; if it’s true, it redirects the request to an
SSL-secured page. Then it is checked for authentication, and so forth.
State
Sometimes you want a component to behave differently for various possible states of the application.
First, de ne an abstract
State class, which is a common interface for various ConcreteStates. All
states provide a
handle() method that provides various behaviors of your component. The Context
class is the core class that wraps a
ConcreteState state object. This design pattern makes sense
when
Context is a complete class that also provides state-independent functionalities. Otherwise,
simple subclassing of
Context would be more ef cient.
Context calls the state->handle() method when processing its own requests. Context also has
methods for switching between States. Depending on which
ConcreteState the state variable holds,
the
state->handle() method provides different behaviors. This can be regarded as emulation of a
partial type change at runtime. You can see a diagram of this pattern in Figure 1-25.
The State pattern, although rather simple, is very useful for application development. One example
is database connection — the database abstraction layer may change its behavior depending on the
current connection state. Another example can be the state of a transaction in an online store — the
c01.indd 25c01.indd 25 1/24/2011 5:45:21 PM1/24/2011 5:45:21 PM