Bridge::Simple is a version of the Bridge and Adapter patterns in the Gang of Four Design Patterns book. In implementing the design pattern in Perl I altered the structure of the pattern subtly.
The source of the module
package Bridge::Simple; use strict; use Carp; sub new { my $class = shift; my $object_ref = shift; my $method_map = shift; my $self = {}; $self->{$_} = $method_map->{$_} for keys %$method_map; $self->{object} = $object_ref; return bless($self, $class); } sub AUTOLOAD { my $self = shift; use vars '$AUTOLOAD'; $AUTOLOAD =~ s/.*:://; croak "no method $AUTOLOAD" unless exists $self->{$AUTOLOAD}; my $method = $self->{$AUTOLOAD}; return $self->{object}->$method(@_); } 1;
A structural diagram of the Bridge pattern for an implementation of a cgi Session object that supports storage of the state of a session:
---------- | Session | | object | ---------- |obj ref: | | $store | ----------------- | \___|____\| Bridge::Simple | | Database| | | /| | | objects:| interface: | $map $obj --------------->| DB_File,| fetch() ---:------------ | SQLite | fetch_ids() : store() : delete() : : ----------- (maps the interface of the using object to the implementation interface, eg, the DB_File implementation) { fetch=>'get_value', fetch_ids=>'get_keys', store=>'set_value', delete=>'delete', }
The Bridge pattern allows using different storage methods. I have tested with SQLite and DB_File based storage.
Client code would construct the bridge to the database module, in this case a DB_File based interface:
my $storage = Bridge::Simple->new( Database::DB_File->new( type=>'db_btree', dbpath=>$path_info{sessionpath}, dbname=>'sessiontree.db', ), $storage_map, );
An adapter would map an interface to an already existing module, such as serializing data:
my $xml_map = { serialize=>'xml_out', deserialize=>'xml_in', }; my $yaml_map = { serialize=>'Dump', deserialize=>'Load', }; my $xml_serializer = Bridge::Simple->new( XML::Simple->new(), $xml_map, ); my $yaml_serializer = Bridge::Simple->new( YAML->new(), $yaml_map, );
In reply to RFC Bridge::Simple by hypochrismutreefuzz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |