in reply to Using closures to achieve data hiding in OO Perl
package UsesClosures; sub new { my $attr; return bless({ get_attr => sub { $attr }, set_attr => sub { $attr = $_[1] }, some_method => sub { print "$attr\n"; } }, shift); } sub get_attr { &{ shift->{get_attr } } }; sub set_attr { &{ shift->{set_attr } } }; sub some_method { &{ shift->{some_method} } };
my $o = UsesClosures->new(); $o->set_attr(123); print $o->get_attr(); $o->some_method();
Your Dinner module would be:
package Dinner; sub new { my $hands_clean = 1; return bless({ wash_hands => sub { $hands_clean = 1; }, eat_food => sub { die "Filthy\n if !$hands_clean; print "Om nom nom\n"; }, }, shift); } sub wash_hands { &{ shift->{wash_hands} } }; sub eat_food { &{ shift->{eat_food } } };
my $dirtyeater = Dinner->new(); $dirtyeater->wash_hands(); $dirtyeater->eat_food();
Like inside-out objects, such objects are hard to debug.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Using closures to achieve data hiding in OO Perl
by saurabh.hirani (Beadle) on Jun 13, 2009 at 05:10 UTC | |
by demerphq (Chancellor) on Jun 13, 2009 at 11:26 UTC | |
by saurabh.hirani (Beadle) on Jun 15, 2009 at 04:45 UTC | |
by demerphq (Chancellor) on Jun 15, 2009 at 12:39 UTC | |
by ikegami (Patriarch) on Jun 13, 2009 at 20:40 UTC |