Thanks for the discussion LanX :-) I think that you're looking for something too complicated, and that Roles just do the trick. (i might well be wrong). Here is the Perl code for getting the same behavior as the Ruby code from the slides (it could all be shorter and put in the same file, with MooseX::Declare - but some people might not have it installed):
test.pl
use feature ':5.16'; use strictures; use Door; use Moose::Util qw( apply_all_roles ); my $main_door = Door->new; # The Door is Closed $main_door->knock; # knock knock # Open it apply_all_roles($main_door, 'Opened'); $main_door->knock; # just come on in! # Close it apply_all_roles($main_door, 'Closed'); $main_door->knock; # knock knock # Bug ?? say 'Why does this not print ??' if $main_door->DOES('Closed');
Door.pm
package Door; use Moo; use feature ':5.16'; use Moose::Util qw( apply_all_roles ); sub BUILD { apply_all_roles($_[0], 'Closed'); # default State at construction } sub knock { say 'DEFECT: a door should never be nor opened nor closed'; # This method will be overriden by the Roles # (should never be printed) } 1;
Closed.pm
package Closed; use Moose::Role; use feature ':5.16'; sub knock { say 'knock knock'; } 1;
Opened.pm
package Opened; use Moose::Role; use feature ':5.16'; sub knock { say 'just come one in!'; } 1;
Which does what is expected (output written as comments in test.pl).
But it has several problems:
If there were simple solutions to these two problems, then i think we could implement complex State machines with multidimensional states.
There is here someone who asked pretty much the same question as me, with a pretty good example of multidimensional State machine: a warrior who can be turned into a Zombie, poisoned, made stronger, turned into a Chipmunk, or all of these at the same time. The answer to that person's question was an alternative solution with aspects. I would still prefer the solution with Roles, which are more flexible, and in my opinion clearer.
Was that clear? Helpful? Did i miss your point LanX?
In reply to Re^4: a State machine with Roles - possible? (class or instance)
by mascip
in thread a State machine with Roles - possible?
by mascip
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |