驼鹿还是元?
我已经尝试了多种方法来做到这一点,但没有一种方法看起来足够优雅。 (我也想知道 CPAN 或 Moose 是否已经有了这个。随着时间的推移,我所做的数十次搜索都没有显示出任何完全匹配的内容。)
我想创建一种类,它
- 是 Base + Facade + Factory 的其他类型将自身加载为目标类型的类。
- “工厂”只是
Base->new( %params )
,它根据各个子类注册的策略创建类型。 - 每个子类都知道有关基类的域的基本知识,但我试图将其保持在最低限度。 请参阅下面的示例:
UnresolvedPath
只知道我们应该首先检查是否存在。
一个明显的例子是文件系统目录和文件:
package Path;
use Moose;
...
sub BUILD {
my ( $self, $params ) = @_;
my $path = $params->{path};
my $class_name;
foreach my $test_sub ( @tests ) {
$class_name = $test_sub->( $path );
last if $class_name;
}
croak "No valid class for $path!" unless defined $class_name;
$class_name->BUILD( $self, $params );
}
package Folder;
use Moose;
extends 'Path';
use Path register => selector => sub { -d $_[0] };
sub BUILD { ... }
package UnresolvedPath;
extends 'Path';
use Path register position => 1, selector => sub { !-e $_[0] };
- 问题:Moose 是否为此提供了一个优雅的解决方案? 或者我是否必须进入 Class::MOP 进行批量处理?
I've been trying to do this a number of ways, but none of them seem graceful enough. (I'm also wondering if CPAN or Moose already has this. The dozens of searches I've done over time have shown nothing that quite matches.)
I want to create a type of class that
- is a Base + Facade + Factory for other classes which load themselves as destination types.
- The "factory" is just
Base->new( %params )
and this creates types based on policies registered by the individual subclass. - Each subclass knows basic things about the domain of the Base class, but I'm trying to keep it minimal. See the example below:
UnresolvedPath
just knows that we should check for existence first.
The obvious example for this is file system directories and files:
package Path;
use Moose;
...
sub BUILD {
my ( $self, $params ) = @_;
my $path = $params->{path};
my $class_name;
foreach my $test_sub ( @tests ) {
$class_name = $test_sub->( $path );
last if $class_name;
}
croak "No valid class for $path!" unless defined $class_name;
$class_name->BUILD( $self, $params );
}
package Folder;
use Moose;
extends 'Path';
use Path register => selector => sub { -d $_[0] };
sub BUILD { ... }
package UnresolvedPath;
extends 'Path';
use Path register position => 1, selector => sub { !-e $_[0] };
- Question: Does Moose provide a graceful solution to this? Or would I have to go into Class::MOP for the bulk?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下 http://code2.0beta.co.uk/moose /svn/MooseX-AbstractFactory/ 并随意窃取。 (矿。)
Have a peek at http://code2.0beta.co.uk/moose/svn/MooseX-AbstractFactory/ and feel free to steal. (Mine.)
如果您确实想要执行构建器模式或抽象工厂模式 那么你就可以做到这一点,没有什么可以阻止你。 但也许您真正需要的是一些 控制反转 / 依赖注入? 为此,您可以查看面包板
If you truely want to do the Builder Pattern or the Abstract Factory Pattern then you can do that, and there is nothing stopping you. But perhaps what you really need is some Inversion of Control / Dependency Injection? For that, you can checkout Bread Board