如何在Perl OO模块中实现调度表? [英] How do I implement a dispatch table in a Perl OO module?

查看:56
本文介绍了如何在Perl OO模块中实现调度表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将OO软件包中的一些子项放入数组(也包含在软件包中)以用作调度表.像这样

I want to put some subs that are within an OO package into an array - also within the package - to use as a dispatch table. Something like this

package Blah::Blah;

use fields 'tests';

sub new {
    my($class )= @_;

    my $self = fields::new($class);

    $self->{'tests'} = [
                         $self->_sub1
                        ,$self->_sub2
                       ];
    return $self;
}

_sub1 { ... };
_sub2 { ... };

我不确定语法吗?

$self->{'tests'} = [
                         $self->_sub1
                        ,$self->_sub2
                       ];

$self->{'tests'} = [
                         \&{$self->_sub1}
                        ,\&{$self->_sub2}
                       ];

$self->{'tests'} = [
                         \&{_sub1}
                        ,\&{_sub2}
                       ];

我似乎无法在OO软件包中使用它,但是它以程序方式非常简单,而且我还没有找到任何面向OO的示例.

I don't seem to be able to get this to work within an OO package, whereas it's quite straightforward in a procedural fashion, and I haven't found any examples for OO.

非常感谢您的帮助, 伊恩

Any help is much appreciated, Iain

推荐答案

尽管

Although Robert P's answer might work for you, it has the problem of fixing the dispatch very early in the process. I tend to resolve the methods as late as I can, so I would leave the things in the tests array as method names until you want to use them:

 $self->{tests} = [
     qw( _sub1 _sub2 )
     ];

动态语言的优势在于,只要您愿意决定要发生什么事情,就可以等待.

The strength of a dynamic language is that you can wait as long as you like to decide what's going to happen.

当您要运行它们时,可以按照罗伯特已经指出的相同过程进行.我会在其中添加一个接口:

When you want to run them, you can go through the same process that Robert already noted. I'd add an interface to it though:

  foreach my $method_name ( $obj->get_test_methods )
      {
      $obj->$method_name();
      }

最好不要将测试与现有方法名称绑定:

That might even be better as not tying the test to an existing method name:

  foreach my $method_name ( $obj->get_test_methods )
      {
      $obj->run_test_named( $method_name );
      }

然后run_test_named可以成为您的调度程序,并且可以非常灵活:

That run_test_named could then be your dispatcher, and it can be very flexible:

 sub run_test_named
      {
      my( $self, $name ) = @_;

      # do anything you want, like in Robert's answer
      }

您可能想做的一些事情:

Some things you might want to do:

  • 在对象上运行方法
  • 将该对象作为参数传递给其他对象
  • 暂时替代测试
  • 什么都不做
  • 等,等等

当您将决定的工作与实施分开时,您将拥有更多的自由.不仅如此,下次您调用相同的测试名称时,您可以做一些不同的事情.

When you separate what you decide to do from its implementation, you have a lot more freedom. Not only that, the next time you call the same test name, you can do something different.

这篇关于如何在Perl OO模块中实现调度表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆