Skip to content

Instantly share code, notes, and snippets.

@yaotti
Created December 28, 2009 04:41
Show Gist options
  • Save yaotti/264534 to your computer and use it in GitHub Desktop.
Save yaotti/264534 to your computer and use it in GitHub Desktop.
design pattern: Chain Of Responsibility
package HTTP::RequestHandler::GET;
use base qw/HTTP::RequestHandler/;
use strict;
use warnings;
sub handle_request {
my ($self, $request) = @_;
return if $request->method ne 'GET';
warn 'Requested method is GET: ' . $request->uri;
}
1;
package HTTP::RequestHandler::POST;
use base qw/HTTP::RequestHandler/;
use strict;
use warnings;
sub handle_request {
my ($self, $request) = @_;
return if $request->method ne 'POST';
warn 'Requested method is POST: ' . $request->uri;
}
1;
#!/usr/bin/env perl
use strict;
use warnings;
use FindBin::libs;
use HTTP::RequestProcessor;
use HTTP::RequestHandler::GET;
use HTTP::RequestHandler::POST;
my $p = HTTP::RequestProcessor->new;
$p->add_handler( HTTP::RequestHandler::GET->new );
$p->add_handler( HTTP::RequestHandler::POST->new );
$p->handle_request( HTTP::Request->new( GET => 'http://github.com' ) );
$p->handle_request( HTTP::Request->new( POST => 'http://github.com' ) );
1;
package HTTP::RequestHandler;
use strict;
use warnings;
use base qw/Class::Accessor::Lvalue::Fast/;
1;
package HTTP::RequestProcessor;
use strict;
use warnings;
use HTTP::RequestHandler;
use HTTP::Request;
use base qw/Class::Accessor::Lvalue::Fast/;
__PACKAGE__->mk_accessors(qw/handlers/);
sub add_handler {
my ($self, $handler) = @_;
push @{$self->{handlers}}, $handler;
$self;
}
sub handle_request {
my ($self, $request) = @_;
for my $handler (@{$self->handlers}) {
$handler->handle_request($request) and return;
}
die "Request could not be handled";
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment