如何将函数传递给构造函数,以便类可以在内部使用它?如何将函数传递给构造函数
test.pl
use Class;
use Loger;
my $loger = Loger->new();
$loger->log('I have logger now, I can log messages!');
my $class = Class->new(\&{ $loger->log }); # here we pass the function (the method of other class) to contructor of a new Class
$class->do_something(); # class uses loger->log internally to report errors
Class.pm 类,包;
sub new {
my $self = {};
$self->{log} = shift; # we got logger->log function, save it for future use
return bless $self;
}
sub do_something {
my $self = shift;
open_file or $self->{log}->('Cant open file'); # we can use gotten logger in class
}
1;
你可能要考虑使用这样的单例模式:http://perldesignpatterns.com/?SingletonPattern。每个需要使用记录器的课程可以调用例如Logger :: getLogger()(或只是Logger-> new()),而不是将其作为构造函数参数。 – RobEarl