我们使用OOP perl作为编程语言来设计这个框架,所以这个类似算法的代码是用perl编写的。
我们正在为一个端点设备开发一个OOP Perl自动化框架。此端点设备提供HTTP、Telnet和SSH接口来执行特定的命令集。为了简单起见,我们可以假设所有命令都受到所有三个连接接口的支持,从而为给定的命令生成相同的输出。
在相应的Connection类中编写了一个函数来处理特定的命令。例如
sub getVersion {
return $http->sendCommand('version');
}
但目前调用此类函数的实现方式几乎没有什么不同。假设,我们想调用getVersion函数,那么它将被这样调用。
$device->getVersion(); //This is called through device object rather than connection object.
由于该函数未在设备类中定义,因此调用AUTOLOAD。在Device类中,AUTOLOAD的实现方式与类似
sub AUTOLOAD {
my $connection = $device->getConnection();
return $connection->$methodName (..); // when called for getVersion, $methodName will become the "getVersion"
}
请让我知道这是实现它的好方法,还是我应该通过为设备类中的每个命令实现一个函数来修改它以删除AUTOLOAD,比如:
sub getVersion {
my $connection = $device->getConnection();
return $connection->getVersion();
}
我们有150多个这样的命令可通过所有三个接口(HTTP、Telnet、SSH)使用。
Class::Delegator
非常适合更清洁的实现。您可能会设计一个作为根行为的类,比如Connected
,它定义了如何获得连接。
{ package Connected;
use Modern::Perl;
sub getConnection {
...
}
}
{ package ConnectedObject;
use Modern::Perl;
use parent 'Connected';
use Class::Delegator
send => [ 'getVersion'
, 'obliterateAllLifeforms'
, ...
]
to => 'getConnection'
;
}