使用 Moose 时在构造时分配方法体的最佳方法是什么? [英] What's the best way to assign a method body at construction time when using Moose?

查看:50
本文介绍了使用 Moose 时在构造时分配方法体的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Moose(特别是 MooseX::Declare)来创建一个迭代器对象,Iter,它有一个 next 方法,根据在 while 语句中使用的需要,推进状态并返回 01.我遇到的问题是,根据其中一个构造参数的存在,next 需要执行两组截然不同的操作.在我看来,我有五个选项:

I'm using Moose (specifically MooseX::Declare) to create an iterator object, Iter which has a next method that advances state and returns 0 or 1 as required for use in a while statement. The problem I'm running into is that depending on the existence of one of the construction parameters, next needs to perform two very different sets of operations. The way I see it I have five options:

  1. if ... then 在 next 方法中
  2. 子类
  3. 哈希调度
  4. 符号表操作
  5. 将方法放在不同的模块中,并在构建时加载所需的方法

No. 1 只是业余爱好者.

数字 2,我想是正确的 OOP 做事方式.我不反对这样做,但仅仅覆盖一个方法似乎有点矫枉过正.

Number 2 is, I suppose, the proper OOP way of doing things. I have no objections to doing it that way but seems a little bit overkill simply to override a single method.

过去我经常在程序性或伪功能性工作时使用 Number 3,这就是我现在正在做的.

I've often used Number 3 in the past when working procedurally or pseudo-functionally and it's what I'm doing now.

数字 4,众所周知,充满危险,我对 Moose Guts 一无所知,不想在不必要的时候开始捣乱.

Number 4 is, as we all know, fraught with peril and I know nothing about Moose Guts to want to start messing around when unnecessary.

最后一项,编号 5 在我看来是最明智的(也是 Perlish),但与编号 2 一样,工作量有点大.我真的想知道是否还有第五种我没有考虑过的方法,比如挂钩到元类或者一个相当成熟的 MooseX 模块.

The last item, number 5 seems to me to be the most sensible (and Perlish) but like Number 2, is a little too much work. I'm really wondering if there's a fifth way I haven't considered such as hooking into the metaclass or perhaps a MooseX module that is reasonably mature.

推荐答案

将您的下一个"子引用传递给构造函数并将其保存在属性中:

Pass your 'next' subref into the constructor and save it in an attribute:

has next => (
    isa => 'CodeRef',
    required => 1,
    traits => ['Code'],
    handles => { next => 'execute_method' },
);

使用 原生属性 'Code' trait,你可以像普通方法一样调用 'next' 方法,它会在属性中找到 subref 主体.

With the 'execute_method' handler provided by the native attribute 'Code' trait, you can call the 'next' method as a normal method and it will find the subref body in the attribute.

如果你想预先定义subref body/ies并在构建时决定使用哪个版本,你可以根据对象的其他条件在builder sub中设置'next'的值:

If you want to pre-define the subref body/ies and decide at construction time which version to use, you could set the value of 'next' in a builder sub according to other conditions of the object:

has next => (
    # ...
    lazy => 1,
    default => sub {
         my $self = shift;
         return sub { ... } if $self->some_condition;
         # etc etc...
    },
);

这篇关于使用 Moose 时在构造时分配方法体的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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