in reply to Command Design Pattern and Rollbacks
Implementing the Command pattern in Perl adequately really shouldn't require much work as it doesn't depend on qualities that one must coerce Perl into exhibiting, like private variables, or private subroutines without resorting to closures1. For this pattern however there is a particularly promising implementation available in Perl due to the fact that almost anything can be an object, including a subroutine. For example:
In this case, when foo() is invoked the first element of @_ contains a reference to the blessed subroutine, which may then be called by dereferencing. More complex versions of foo() might allow parameters to be passed to the subroutine to vary behavior in whatever way you need, or the module might define additional methods that call the subroutine in various ways. Take a look at TheDamian's Object Oriented Perl chapter 5.2 for (much) more.package Action; sub new { my ($class, %args) = @_; my $coderef = sub { while (my ($k, $v) = each(%args)) { ... } }; return bless($coderef, $class); } sub foo { $_[0]->(); }
And now a word of caution. It sounds like this is a first draft of a very complicated system. I think it's highly likely that you'll discover as you go many many problems and requirements that you had not anticipated. And though patterns can yield great elegance and capability, if implemented without a clear vision they will fast begin to feel like concrete shoes. (see Design Patterns Considered Harmful) I strongly suggest a prototype free of patterns. Once you've thoroughly mapped out what the system requirements are, then go back and rewrite using patterns (if they're still applicable at that point).
package SingletonObject; { my $instance; sub instance { unless (defined $instance) { $instance = bless ({}, $class); # other initialization stuff } return $instance; } }
|
|---|