Announcements
view release on metacpan or search on metacpan
lib/Announcements.pm view on Meta::CPAN
package Announcements;
our $VERSION = '0.01';
1;
__END__
=head1 NAME
Announcements - communicate across the object network
=head1 DESCRIPTION
This Announcements library implements a relatively simple extension
of the observer pattern for permitting the observers of an event to
communicate amongst eachother and with the publisher of the event. Many
implementations of the observer pattern use fixed strings as events, but
Announcements uses objects. Indeed, any object can be announced, and
each observer can call whichever methods on that object that it wishes.
=head1 EXAMPLE
The hello world of announcements is observing a value that changes. So
let's walk through such an implementation. You'll probably be adding
announcements to existing code only once you discover that you need the
observer pattern, so let's start with something whose values changes and
then add announcement logic to it.
package NetHack::Character;
use Moose;
has x => (is => 'rw', isa => 'Num');
has y => (is => 'rw', isa => 'Num');
# teleport to a random spot on the map
sub teleport {
my $self = shift;
my $new_x = rand();
my $new_y = rand();
$self->x($new_x);
$self->y($new_y);
}
=head2 Observation
Say we want to track whether the character has ever teleported. Because
teleportation can be used to escape from difficult fights, you could
have a special challenge for beating the game without teleporting. We
could implement this by changing the teleport function.
sub teleport {
my $self = shift;
my $new_x = rand();
my $new_y = rand();
$self->x($new_x);
$self->y($new_y);
$self->has_ever_teleported(1);
}
But instead let's write it as an announcement so that we can decouple
the teleportation logic from the conduct logic. The first step is to
declare an announcement class that represents the "we are about to
teleport" event.
package NetHack::Announcement::Teleporting;
use Moose;
# that's all!
Then we can announce objects of this class in C<teleport>.
sub teleport {
my $self = shift;
$self->announce('NetHack::Announcement::Teleporting');
my $new_x = rand();
my $new_y = rand();
$self->x($new_x);
$self->y($new_y);
}
Finally we set up an observer that flips the C<has_ever_teleported> bit
upon teleport.
$character->add_subscription(
criterion => 'NetHack::Announcement::Teleporting',
action => sub {
my ($announcement, $character) = @_;
$character->has_ever_teleported(1);
},
);
=head2 Communication
Teleports always send you to a random spot on the map. But say you want
to implement an artifact that grants teleport control. If the character
is holding this artifact and is teleported, then the player can pick
the teleport's destination.
package NetHack::Item::MasterKeyOfThievery;
use Moose;
with 'NetHack::Item::Artifact';
sub
Some levels in our game forbid teleportation for various reasons. Let's
( run in 0.688 second using v1.01-cache-2.11-cpan-c966e8aa7e8 )