I have the following UML diagram. CurlRequestHandler
and KernelRequestHandler
are both an implementation of the RequestHandlerInterface
. The request handlers are responsible to process a certain Request
object, all of them will return the same Response
object.
+------------------------+ +-------------------------+
| CurlRequestHandler | | KernelRequestHandler |
|------------------------| |-------------------------|
| | | |
| - handleRequest(Request) | - handleRequest(Request)|
| | | |
| | | |
| | | |
+------------------------+ +-------------------------+
+
| +
| |
| +---------------------------+ |
| | RequestHandlerInterface | | +---------------+
+----> |---------------------------| <-----+ | |
| | | |
| - handleRequest(Request) | | CLIENT |
| | | |
| | +---------------+
| |
| |
+---------------------------+
Now, to determine which handler I need to use, I have the following if statement in my client
:
if ($mode == "kernel") {
$handler = new KernelRequestHandler();
} else {
$handler = new CurlRequestHandler();
}
$response = $handler->handleRequest($request);
Now, the problem is, when I need to add a new handler, I need to alter the if
statement. I looked into the Chain of Responsibility
design pattern and this seems to do a better job at this, but I'm not sure.
Which design pattern would be the best approach for this?
Steffen
What you need is to implement a factory method design pattern to create the handlers.
class HandlerFactory {
public function make($mode) {
switch(strtolower($mode)) {
case 'kernel': return new KernelRequestHandler();
case 'curl': return new CurlRequestHandler();
}
}
}
And, yes, you need to add a case for every new handler you make.